[Interview Questions] How to use the aggregation function of Stream

Sometimes the blog content will change. The first blog is the latest, and other blog addresses may not be synchronized. Check it carefully.https://blog.zysicyj.top

First blog address

Series article address


  1. Sum:
List<Integer> numbers = Arrays.asList(12345);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
  1. Find the average:
List<Integer> numbers = Arrays.asList(12345);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("Average: " + average);
  1. Maximum value (Max):
List<Integer> numbers = Arrays.asList(12345);
int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
System.out.println("Max: " + max);
  1. Minimum value (Min):
List<Integer> numbers = Arrays.asList(12345);
int min = numbers.stream().mapToInt(Integer::intValue).min().orElse(0);
System.out.println("Min: " + min);
  1. Count (Count): You can use count() the method to count the number of elements in the Stream.
List<Integer> numbers = Arrays.asList(12345);
long count = numbers.stream().count();
System.out.println("Count: " + count);
  1. Joining: You can use collect() method combination Collectors.joining() to connect the elements in the Stream into a string.
List<String> names = Arrays.asList("Alice""Bob""Charlie");
String joinedNames = names.stream().collect(Collectors.joining(", "));
System.out.println("Joined Names: " + joinedNames);
  1. Grouping: You can use collect() method combination Collectors.groupingBy() to group elements in a Stream based on a certain attribute.
List<Person> people = Arrays.asList(
    new Person("Alice"25),
    new Person("Bob"30),
    new Person("Charlie"25)
);
Map<Integer, List<Person>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge));
System.out.println("People grouped by age: " + peopleByAge);
  1. Summarizing: You can use collect() method combination Collectors.summarizingInt() and other methods to obtain summary information of elements, such as sum, average, maximum value, minimum value, etc.
List<Integer> numbers = Arrays.asList(12345);
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());

This article is published by mdnice multi-platform

Guess you like

Origin blog.csdn.net/njpkhuan/article/details/132752391