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
-
Sum:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("Sum: " + sum);
-
Find the average:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
double average = numbers.stream().mapToInt(Integer::intValue).average().orElse(0.0);
System.out.println("Average: " + average);
-
Maximum value (Max):
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int max = numbers.stream().mapToInt(Integer::intValue).max().orElse(0);
System.out.println("Max: " + max);
-
Minimum value (Min):
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int min = numbers.stream().mapToInt(Integer::intValue).min().orElse(0);
System.out.println("Min: " + min);
-
Count (Count): You can use count()
the method to count the number of elements in the Stream.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
long count = numbers.stream().count();
System.out.println("Count: " + count);
-
Joining: You can use collect()
method combinationCollectors.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);
-
Grouping: You can use collect()
method combinationCollectors.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);
-
Summarizing: You can use collect()
method combinationCollectors.summarizingInt()
and other methods to obtain summary information of elements, such as sum, average, maximum value, minimum value, etc.
List<Integer> 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());
This article is published by mdnice multi-platform