Java 8 introduced the Stream API, which provides a functional programming approach to processing collection data. The Stream API provides a wealth of operation methods, which can filter, map, sort and other operations on collections. The following are some commonly used Stream collection operations:
- Filter: Use
filter
this method to filter out the elements in the collection that meet the specified conditions. For example:List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList());
In the above code,
filter
the method filters out even numbers in the list. - Map: Use
map
methods to transform elements in a collection. For example:List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<Integer> nameLengths = names.stream() .map(String::length) .collect(Collectors.toList());
In the above code,
map
the method converts each element in the string list to its length. - Sort: Use
sorted
methods to sort elements in a collection. For example:List<String> names = Arrays.asList("Alice", "Bob", "Charlie"); List<String> sortedNames = names.stream() .sorted() .collect(Collectors.toList());
In the above code,
sorted
the method alphabetically sorts the string list. - Match: Use the
anyMatch
,allMatch
andnoneMatch
methods to determine whether the elements in the collection meet specified conditions. For example:List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); boolean anyMatch = numbers.stream().anyMatch(n -> n > 3); boolean allMatch = numbers.stream().allMatch(n -> n > 0); boolean noneMatch = numbers.stream().noneMatch(n -> n < 0);
In the above code,
anyMatch
the method determines whether there are elements greater than 3 in the set,allMatch
the method determines whether all elements in the set are greater than 0, andnoneMatch
the method determines whether there are no elements less than 0 in the set. - Reduce: Use
reduce
methods to perform reduction operations on elements in a collection, such as summing, maximizing, etc. For example:List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream().reduce(0, (a, b) -> a + b); Optional<Integer> max = numbers.stream().reduce(Integer::max);
In the above code,
reduce
the method sums the elements in the collection, the first parameter is the initial value, and the second parameter is the reduction operation.These are just some common operations provided by the Stream API, and there are other rich operation methods that can be used according to actual needs. It should be noted that Stream operations are lazily evaluated and will only be executed when the operation is terminated (such as
collect
,forEach
etc.).