有的时候博客内容会有变动,首发博客是最新的,其他博客地址可能会未同步,认准
https://blog.zysicyj.top
首发博客地址
系列文章地址
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
List numbers = Arrays.asList(1, 2, 3, 4, 5);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("Average: " + average);
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
System.out.println("Max: " + max);
List numbers = Arrays.asList(1, 2, 3, 4, 5);
int min = numbers.stream().mapToInt(Integer::intValue).min().orElse(0);
System.out.println("Min: " + min);
count()
方法来计算Stream中元素的个数。 List numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
System.out.println("Count: " + count);
collect()
方法结合 Collectors.joining()
来将Stream中的元素连接成一个字符串。 List names = Arrays.asList("Alice", "Bob", "Charlie");
String joinedNames = names.stream().collect(Collectors.joining(", "));
System.out.println("Joined Names: " + joinedNames);
collect()
方法结合 Collectors.groupingBy()
来根据某个属性对Stream中的元素进行分组。 List people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25)
);
Map> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
System.out.println("People grouped by age: " + peopleByAge);
collect()
方法结合 Collectors.summarizingInt()
等方法来获取元素的汇总信息,如求和、平均值、最大值、最小值等。 List numbers = Arrays.asList(1, 2, 3, 4, 5);
IntSummaryStatistics stats = numbers.stream().collect(Collectors.summarizingInt(Integer::intValue));
System.out.println("Sum: " + stats.getSum());
System.out.println("Average: " + stats.getAverage());
System.out.println("Max: " + stats.getMax());
System.out.println("Min: " + stats.getMin());
本文由 mdnice 多平台发布