Java8 Stream Collectors收集器使用方法解析
阿新 • • 發佈:2020-08-06
Collectors.toMap:
Student studentA = new Student("20190001","小明"); Student studentB = new Student("20190002","小紅"); Student studentC = new Student("20190003","小丁"); //Function.identity() 獲取這個物件本身,那麼結果就是Map<String,Student> 即 id->student //序列收集 Stream.of(studentA,studentB,studentC) .collect(Collectors.toMap(Student::getId,Function.identity())); //併發收集 Stream.of(studentA,studentC) .parallel() .collect(Collectors.toConcurrentMap(Student::getId,Function.identity())); //================================================================================ //Map<String,String> 即 id->name //序列收集 Stream.of(studentA,Student::getName)); //併發收集 Stream.of(studentA,Student::getName));
那麼如果key重複的該怎麼處理?這裡我們假設有兩個id相同Student,如果他們id相同,在轉成Map的時候,取name大一個,小的將會被丟棄。
//Map<String,Student> //maxby ==sordBy 倒序 minBy or .maxBy(Comparator.comparing(User::getName).reversed()))); Stream.of(studentA,studentC) .collect(Collectors .toMap(Student::getId,Function.identity(),BinaryOperator .maxBy(Comparator.comparing(Student::getName)))); //可能上面比較複雜,這編寫一個命令式 //Map<String,Student> Stream.of(studentA,(s1,s2) -> { //這裡使用compareTo 方法 s1>s2 會返回1,s1==s2 返回0 ,否則返回-1 if (((Student) s1).name.compareTo(((Student) s2).name) < -1) { return s2; } else { return s1; } }));
如果不想使用預設的HashMap 或者 ConcurrentHashMap,第三個過載方法還可以使用自定義的Map物件(Map工廠)。
//自定義LinkedHashMap //Map<String,BinaryOperator .maxBy(Comparator.comparing(Student::getName)),LinkedHashMap::new));
Collectors.groupingBy()和Collectors.groupingByConcurrent(),這兩者區別也僅是單執行緒和多執行緒的使用場景。為什麼要groupingBy歸類為前後處理呢?groupingBy 是在資料收集前分組的,再將分好組的資料傳遞給下游的收集器。
這是 groupingBy最長的引數的函式classifier 是分類器,mapFactory map的工廠,downstream下游的收集器,正是downstream 的存在,可以在資料傳遞個下游之前做很多的騷操作。
public static <T,K,D,A,M extends Map<K,D>> Collector<T,?,M> groupingBy(Function<? super T,? extends K> classifier,Supplier<M> mapFactory,Collector<? super T,D> downstream)
示例:這裡將一組數整型數分為正數、負數、零,groupingByConcurrent()的引數也是跟它一樣的就不舉例了。
//Map<String,List<Integer>> Stream.of(-6,-7,-8,-9,1,2,3,4,5,6) .collect(Collectors.groupingBy(integer -> { if (integer < 0) { return "小於"; } else if (integer == 0) { return "等於"; } else { return "大於"; } })); //Map<String,Set<Integer>> //自定義下游收集器 Stream.of(-6,6) .collect(Collectors.groupingBy(integer -> { if (integer < 0) { return "小於"; } else if (integer == 0) { return "等於"; } else { return "大於"; } },Collectors.toSet())); //Map<String,Set<Integer>> //自定義map容器 和 下游收集器 Stream.of(-6,LinkedHashMap::new,Collectors.toSet()));
Collectors.partitioningBy()
字面意思話就叫分割槽好了,但是partitioningBy最多隻能將資料分為兩部分,因為partitioningBy分割槽的依據Predicate,而Predicate只會有true 和false 兩種結果,所有partitioningBy最多隻能將資料分為兩組。partitioningBy除了分類器與groupingBy 不一樣外,其他的引數都相同。
示例:
//Map<Boolean,List<Integer>> Stream.of(0,1) .collect(Collectors.partitioningBy(integer -> integer==0)); //Map<Boolean,Set<Integer>> //自定義下游收集器 Stream.of(0,1) .collect(Collectors.partitioningBy(integer -> integer==0,Collectors.toSet()));
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。