本文共 12943 字,大约阅读时间需要 43 分钟。
java 根据类名示例化类
Java Collectors is a utility class that provides many useful implementations of the Collector interface. The Collector implementation is used with the method. This class was introduced in Java 8 along with Stream API. The Collectors is a final class and all the methods are static that returns the Collector instance.
Java Collectors是一个实用程序类,提供了Collector接口的许多有用的实现。 Collector实现与方法一起使用。 此类在Java 8中与Stream API一起引入。 收集器是最终类,所有方法都是静态的,返回收集器实例。
Some of the popular Java Collectors methods are:
一些流行的Java Collectors方法是:
Let’s look at the examples of Collectors functions with simple examples.
让我们用简单的示例看一下Collectors函数的示例。
This function returns a Collector that accumulates the input elements into a collection.
此函数返回一个收集器,该收集器将输入元素累积到一个集合中。
ListstrList = Arrays.asList("a", "b", "c", "b", "a");// toCollection()Collection strCollection = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));System.out.println(strCollection); // [a, b, c]Set strSet = strList.parallelStream().collect(Collectors.toCollection(HashSet::new));System.out.println(strSet); // [a, b, c]List strList1 = strList.parallelStream().sorted(String::compareToIgnoreCase) .collect(Collectors.toCollection(ArrayList::new));System.out.println(strList1); // [a, a, b, b, c]
It returns a Collector that accumulates the input elements into a new List.
它返回一个收集器,该收集器将输入元素累积到一个新的列表中。
ListstrList = Arrays.asList("a", "b", "c", "b", "a");List uppercaseList = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toList());System.out.println(uppercaseList); // [A, B, C, B, A]List uppercaseUnmodifiableList = strList.parallelStream().map(String::toUpperCase) .collect(Collectors.toUnmodifiableList());System.out.println(uppercaseUnmodifiableList); // [A, B, C, B, A]
This method returns the Collector that accumulates the input elements into a new Set.
此方法返回将输入元素累积到新Set中的收集器。
ListstrList = Arrays.asList("a", "b", "c", "b", "a");Set uppercaseSet = strList.parallelStream().map(String::toUpperCase).collect(Collectors.toSet());System.out.println(uppercaseSet); // [A, B, C]Set uppercaseUnmodifiableSet = strList.parallelStream().map(String::toUpperCase) .collect(Collectors.toUnmodifiableSet());System.out.println(uppercaseUnmodifiableSet); // [A, B, C]
This static method returns a Collector to accumulate input elements into a new Map. We have to specify the mapping functions to generate the map keys and values.
此静态方法返回收集器,以将输入元素累积到新的Map中。 我们必须指定映射函数以生成映射键和值。
Mapmap = Stream.of("a", "b", "c") .collect(Collectors.toMap(Function.identity(), String::toUpperCase));System.out.println(map); // {a=A, b=B, c=C}// Duplicate Keys will throw: Exception in thread "main"// java.lang.IllegalStateException: Duplicate key a (attempted merging values A// and A)Map mapD = Stream.of("a", "b", "c", "b", "a") .collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat));System.out.println(mapD); // {a=AA, b=BB, c=C}// above are HashMap, use below to create different types of MapTreeMap mapTree = Stream.of("a", "b", "c", "b") .collect(Collectors.toMap(Function.identity(), String::toUpperCase, String::concat, TreeMap::new));System.out.println(mapTree); {a=A, b=BB, c=C}
It returns a Collector that concatenate the input CharSequence elements into a new string. There are few overloaded methods to specify the delimiter and suffix/prefix strings.
它返回一个收集器,该收集器将输入的CharSequence元素连接到一个新字符串中。 很少有重载的方法来指定定界符和后缀/前缀字符串。
String concat = Stream.of("a", "b").collect(Collectors.joining());System.out.println(concat); // abString csv = Stream.of("a", "b").collect(Collectors.joining(","));System.out.println(csv); // a,bString csv1 = Stream.of("a", "b").collect(Collectors.joining(",", "[", "]"));System.out.println(csv1); // [a,b]String csv2 = Stream.of("a", new StringBuilder("b"), new StringBuffer("c")).collect(Collectors.joining(","));System.out.println(csv2); // a,b
This method returns a Collector that applies the Function to the input elements and then accumulate them to the given Collector.
此方法返回一个收集器,该收集器将函数应用于输入元素,然后将其累加到给定的收集器。
SetsetStr = Stream.of("a", "a", "b") .collect(Collectors.mapping(String::toUpperCase, Collectors.toSet()));System.out.println(setStr); // [A, B]Set setStr1 = Stream.of("a", "a", "b") .collect(Collectors.flatMapping(s -> Stream.of(s.toUpperCase()), Collectors.toSet()));System.out.println(setStr1); // [A, B]
It returns a Collector that applies the Predicate to the input elements and accumulate them to the given Collector if the predicate returns true.
它返回一个收集器,该收集器将谓词应用于输入元素,如果谓词返回true,则将它们累加到给定的收集器。
ListstrList2 = List.of("1", "2", "10", "100", "20", "999");Set set = strList2.parallelStream() .collect(Collectors.filtering(s -> s.length() < 2, Collectors.toSet()));System.out.println(set); // [1, 2]
This static method returns a Collector that accumulates the input elements into the given Collector and then perform an additional finishing function.
此静态方法返回一个收集器,该收集器将输入元素累积到给定的收集器中,然后执行附加的整理功能。
ListstrList2 = List.of("1", "2", "10", "100", "20", "999");List unmodifiableList = strList2.parallelStream() .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));System.out.println(unmodifiableList); // [1, 2, 10, 100, 20, 999]
This function returns a Collector that counts the number of the input elements.
该函数返回一个收集器,该收集器对输入元素的数量进行计数。
Long evenCount = Stream.of(1, 2, 3, 4, 5).filter(x -> x % 2 == 0).collect(Collectors.counting());System.out.println(evenCount); // 2
It returns a Collector that returns the minimum element based on the given comparator.
它返回一个收集器,该收集器根据给定的比较器返回最小元素。
Optionalmin = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> x - y));System.out.println(min); // Optional[1]
This method returns a Collector that returns the maximum element based on the given comparator.
此方法返回一个收集器,该收集器根据给定的比较器返回最大元素。
Optionalmax = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> y - x));System.out.println(max); // Optional[5]
This static method returns a Collector that produces the sum of a integer-valued function applied to the input elements. There are similar functions for long and double – summingLong(ToLongFunction) and summingDouble(ToDoubleFunction).
此静态方法返回一个收集器,该收集器产生应用于输入元素的整数函数的总和。 long和double都有类似的功能-summingLong(ToLongFunction)和summingDouble(ToDoubleFunction)。
ListstrList3 = Arrays.asList("1", "2", "3", "4", "5");Integer sum = strList3.parallelStream().collect(Collectors.summingInt(Integer::parseInt));System.out.println(sum); // 15Long sumL = Stream.of("12", "23").collect(Collectors.summingLong(Long::parseLong));System.out.println(sumL); // 35Double sumD = Stream.of("1e2", "2e3").collect(Collectors.summingDouble(Double::parseDouble));System.out.println(sumD); // 2100.0
It returns a Collector that produces the arithmetic mean of an integer-valued function applied to the input elements. There are similar functions for long and double – averagingLong(ToLongFunction) and averagingDouble(ToDoubleFunction).
它返回一个收集器,该收集器产生应用于输入元素的整数函数的算术平均值。 长整型和双精度型也有类似的功能– averagingLong(ToLongFunction)和averagingDouble(ToDoubleFunction)。
ListstrList4 = Arrays.asList("1", "2", "3", "4", "5");Double average = strList4.parallelStream().collect(Collectors.averagingInt(Integer::parseInt));System.out.println(average); // 3.0Double averageL = Stream.of("12", "23").collect(Collectors.averagingLong(Long::parseLong));System.out.println(averageL); // 17.5Double averageD = Stream.of("1e2", "2e3").collect(Collectors.averagingDouble(Double::parseDouble));System.out.println(averageD); // 1050.0
This method returns a Collector implementing a “group by” operation on input elements. The final result is a HashMap. There are few overloaded methods to specify the Supplier (final Map type, default is HashMap) and Collector (Value List type, default is ArrayList).
此方法返回在输入元素上实现“分组依据”操作的收集器。 最终结果是一个HashMap。 很少有重载的方法来指定Supplier(最终Map类型,默认为HashMap)和Collector(Value List类型,默认为ArrayList)。
Map> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3) .collect(Collectors.groupingBy(x -> x * 10));System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}
It works in the same way as groupingBy() Collector. The only difference is that the Collector is concurrent and unordered. It will have better performance than the groupingBy() Collector but the ordering will not be maintained.
它的工作方式与groupingBy()收集器相同。 唯一的区别是收集器是并发且无序的。 它会比groupingBy()收集器具有更好的性能,但不会保持排序。
Map> mapGroupBy = Stream.of(1, 2, 3, 4, 5, 4, 3) .collect(Collectors.groupingByConcurrent(x -> x * 10));System.out.println(mapGroupBy); // {50=[5], 20=[2], 40=[4, 4], 10=[1], 30=[3, 3]}
This method returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map<Boolean, List<T>>.
此方法返回一个收集器,该收集器根据谓词对输入元素进行分区,并将它们组织成Map <Boolean,List <T >>。
Map> mapPartitionBy = Stream.of(1, 2, 3, 4, 5, 4, 3) .collect(Collectors.partitioningBy(x -> x % 2 == 0));System.out.println(mapPartitionBy); // {false=[1, 3, 5, 3], true=[2, 4, 4]}
It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator. This is mostly used in a multi-level reduction, such as specifying downstream Collector with groupingBy() and partitioningBy() methods.
它返回一个收集器,该收集器在指定的BinaryOperator下执行其输入元素的缩减。 这主要用于多级归约中,例如使用groupingBy()和partitioningBy()方法指定下游Collector。
Map> reducing = Stream.of(1, 2, 3, 4, 5, 4, 3).collect(Collectors.partitioningBy( x -> x % 2 == 0, Collectors.reducing(BinaryOperator.maxBy(Comparator.comparing(Integer::intValue)))));System.out.println(reducing); // {false=Optional[5], true=Optional[4]}
It returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values such as min, max, average, count, and count.
它返回一个收集器,该收集器将一个生成整数的映射函数应用于每个输入元素,并返回结果统计值的摘要,例如最小值,最大值,平均值,计数和计数。
IntSummaryStatistics summarizingInt = Stream.of("12", "23", "35") .collect(Collectors.summarizingInt(Integer::parseInt));System.out.println(summarizingInt);//IntSummaryStatistics{count=3, sum=70, min=12, average=23.333333, max=35}
Java Collectors class static methods are very useful in creating Collector instance to use with Stream collect() method. It covers almost all the most popular scenarios.
Java Collectors类的静态方法在创建与Stream collect()方法一起使用的Collector实例时非常有用。 它涵盖了几乎所有最流行的方案。
翻译自:
java 根据类名示例化类
转载地址:http://dmlzd.baihongyu.com/