java - collect
来源:趣味经验馆 2.38W
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java collect是什么,让我们一起了解一下:
collect是一个终端操作,接收的参数是将流中的元素累积到汇总结果的各种方式(称为收集器),collect主要依赖java.util.stream.Collectors类内置的静态方法。
那么在流中的数据完成处理后,该如何将流中的数据重新归集到新的集合里?
因为流不存储数据,那么在流中的数据完成处理后,需要将流中的数据重新归集到新的集合里叫归集,toList、toSet和toMap比较常用,另外还有toCollection、toConcurrentMap等复杂一些的用法。
具体操作代码如下:
List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20); List<Integer> listNew = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); System.out.println("产生的新集合是:" + listNew); Set<Integer> set = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); System.out.println("产生的不重复的新集合是:" + set); List<Person> personList = new ArrayList<>(); personList.add(new Person("Tom", 8900, 22, "male", "New Yark")); personList.add(new Person("Jack", 7000, 29, "male", "Washington")); personList.add(new Person("Lily", 7800, 24, "female", "Washington")); personList.add(new Person("Anni", 8200, 28, "female", "New Yark")); personList.add(new Person("Owen", 9500, 26, "male", "New Yark")); personList.add(new Person("Alisa", 7900, 27, "female", "New Yark")); Map<?, Person> personMap = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p)); System.out.println("产生的新的map集合是:" + personMap);
拓展一下:在java中,流stream中的collect()方法详解如下:
List<String> vowels = List.of("a", "e", "i", "o", "u");// sequential stream - nothing to combineStringBuilder result = vowels.stream().collect(StringBuilder::new, (x, y) -> x.append(y),(a, b) -> a.append(",").append(b));System.out.println(result.toString());// parallel stream - combiner is combining partial resultsStringBuilder result1 = vowels.parallelStream().collect(StringBuilder::new, (x, y) -> x.append(y),(a, b) -> a.append(",").append(b));System.out.println(result1.toString());