博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 根据类名示例化类_Java收集器类– 18个示例
阅读量:2541 次
发布时间:2019-05-11

本文共 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一起引入。 收集器是最终类,所有方法都是静态的,返回收集器实例。

Java收集器方法 (Java Collectors Methods)

Some of the popular Java Collectors methods are:

一些流行的Java Collectors方法是:

  • toCollection(Supplier)

    toCollection(供应商)
  • toList()

    toList()
  • toSet()

    设置()
  • toMap(Function, Function)

    toMap(函数,函数)
  • joining()

    join()
  • mapping(Function, Collector)

    映射(函数,收集器)
  • filtering(Predicate, Collector)

    过滤(谓词,收集器)
  • collectingAndThen(Collector, Function)

    collectionAndThen(收藏家,函数)
  • counting()

    数数()
  • minBy(Comparator)

    minBy(比较器)
  • maxBy(Comparator)

    maxBy(比较器)
  • summingInt(ToIntFunction), summingLong(ToLongFunction), summingDouble(ToDoubleFunction)

    summingInt(ToIntFunction),summingLong(ToLongFunction),summingDouble(ToDoubleFunction)
  • averagingInt(ToIntFunction), averagingLong(ToLongFunction), averagingDouble(ToDoubleFunction)

    averagingInt(ToIntFunction),averagingLong(ToLongFunction),averagingDouble(ToDoubleFunction)
  • groupingBy(Function)

    groupingBy(功能)
  • groupingByConcurrent(Function)

    groupingByConcurrent(函数)
  • partitioningBy(Predicate)

    partitioningBy(谓词)
  • reducing(BinaryOperator)

    减少(BinaryOperator)
  • summarizingInt(ToIntFunction)

    summarizingInt(ToIntFunction)

Java收集器示例 (Java Collectors Examples)

Let’s look at the examples of Collectors functions with simple examples.

让我们用简单的示例看一下Collectors函数的示例。

1. toCollection(供应商) (1. toCollection(Supplier))

This function returns a Collector that accumulates the input elements into a collection.

此函数返回一个收集器,该收集器将输入元素累积到一个集合中。

List
strList = 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]

2. Java收集器toList() (2. Java Collectors toList())

It returns a Collector that accumulates the input elements into a new List.

它返回一个收集器,该收集器将输入元素累积到一个新的列表中。

List
strList = 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]
Java Collectors toList

Java Collectors toList

Java收藏家toList

3. Java收集器toSet() (3. Java Collectors toSet())

This method returns the Collector that accumulates the input elements into a new Set.

此方法返回将输入元素累积到新Set中的收集器。

List
strList = 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]

4. Java收集器toMap(Function,Function) (4. Java Collectors toMap(Function, Function))

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中。 我们必须指定映射函数以生成映射键和值。

Map
map = 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}

5. Java收集器join() (5. Java Collectors joining())

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

6. Java收集器映射(函数,收集器) (6. Java Collectors mapping(Function, Collector))

This method returns a Collector that applies the Function to the input elements and then accumulate them to the given Collector.

此方法返回一个收集器,该收集器将函数应用于输入元素,然后将其累加到给定的收集器。

Set
setStr = 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]

7.过滤(谓词,收集器) (7. filtering(Predicate, Collector))

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,则将它们累加到给定的收集器。

List
strList2 = 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]

8. collectionAndThen(Collector,Function) (8. collectingAndThen(Collector, Function))

This static method returns a Collector that accumulates the input elements into the given Collector and then perform an additional finishing function.

此静态方法返回一个收集器,该收集器将输入元素累积到给定的收集器中,然后执行附加的整理功能。

List
strList2 = 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]

9. counting() (9. counting())

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

10. minBy(比较器) (10. minBy(Comparator))

It returns a Collector that returns the minimum element based on the given comparator.

它返回一个收集器,该收集器根据给定的比较器返回最小元素。

Optional
min = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> x - y));System.out.println(min); // Optional[1]

11. maxBy(比较器) (11. maxBy(Comparator))

This method returns a Collector that returns the maximum element based on the given comparator.

此方法返回一个收集器,该收集器根据给定的比较器返回最大元素。

Optional
max = Stream.of(1, 2, 3, 4, 5).collect(Collectors.minBy((x, y) -> y - x));System.out.println(max); // Optional[5]

12. summingInt(ToIntFunction) (12. summingInt(ToIntFunction))

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)。

List
strList3 = 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

13. averagingInt(ToIntFunction) (13. averagingInt(ToIntFunction))

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)。

List
strList4 = 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

14. Java收集器分组(按功能) (14. Java Collectors groupingBy(Function))

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]}

15. groupingByConcurrent(函数) (15. groupingByConcurrent(Function))

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]}

16. partitioningBy(谓词) (16. partitioningBy(Predicate))

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]}

17. Java Collector精简(BinaryOperator) (17. Java Collectors reducing(BinaryOperator))

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]}

18. summarizingInt(ToIntFunction) (18. summarizingInt(ToIntFunction))

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}

结论 (Conclusion)

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实例时非常有用。 它涵盖了几乎所有最流行的方案。

参考资料 (References)

翻译自:

java 根据类名示例化类

转载地址:http://dmlzd.baihongyu.com/

你可能感兴趣的文章
main(argc,argv[])
查看>>
在线教育工具—白板系统的迭代1——bug监控排查
查看>>
121. Best Time to Buy and Sell Stock
查看>>
hdu 1005 根据递推公式构造矩阵 ( 矩阵快速幂)
查看>>
安装php扩展
查看>>
百度移动搜索主要有如下几类结果构成
查看>>
Python爬虫面试题170道:2019版【1】
查看>>
JavaBean规范
查看>>
第四阶段 15_Linux tomcat安装与配置
查看>>
NAS 创建大文件
查看>>
学习笔记-模块之xml文件处理
查看>>
接口测试用例
查看>>
面试:用 Java 实现一个 Singleton 模式
查看>>
Sybase IQ导出文件的几种方式
查看>>
案例:手动输入一个字符串,打散放进一个列表,小写字母反序 大写字母保持不变...
查看>>
linux 系统下 tar 的压缩与解压缩命令
查看>>
阿里负载均衡,配置中间证书问题(在starcom申请免费DV ssl)
查看>>
转:How to force a wordbreaker to be used in Sharepoint Search
查看>>
MySQL存储过程定时任务
查看>>
Python中and(逻辑与)计算法则
查看>>