import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class StreamApiCollectExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// 1. 将流中元素收集到List
List<Integer> collectedToList = numbers.stream()
.collect(Collectors.toList());
System.out.println(collectedToList);
// 2. 将流中元素收集到Set
// 注意:Set会过滤重复元素
List<Integer> collectedToSet = numbers.stream()
.collect(Collectors.toSet());
System.out.println(collectedToSet);
// 3. 将流中元素收集到Map
// 使用对象的某个属性作为key,其它属性或者对象本身作为value
List<String> collectedToMap = Arrays.asList("Hello", "World", "Hello", "Java");
Map<String, Long> wordCount = collectedToMap.stream()
.collect(Collectors.toMap(
s -> s, // key为字符串本身
s -> (long) s.length(), // value为字符串长度
(s1, s2) -> s1 // 如果有重复的key,则选择第一个
));
System.out.println(wordCount);
// 4. 收集流中对象的属性到一个Collection
List<Person> people = Arrays.asList(new Person("John", 30), new Person("Sarah", 25));
List<String> names = people.stream()
.map(Person::getName) // 获取每个Person的name
.collect(Collectors.toList());
System.out.println(names);
// 5. 计算流中元素的统计信息
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("最小值:" + stats.getMin());
System.out.println("最大值:" + stats.getMax());
System.out.println("平均值:" + stats.getAverage());
System.out.println("总和:" + stats.getSum());
System.out.println("个数:" + stats.getCount());
评论已关闭