collect(toList())
Generating a list from values in Stram is an early evaluation operation
List<String> collect = Stream.of("a", "b", "c") // Generate a Stream from a list .collect(Collectors.toList()); // Generate a list from Stream
map
Convert a value of one type to another, and a value in a flow to a new flow
// Replace strings in a collection with uppercase List<String> collect = Stream.of("a", "b", "hello").map(string -> string.toUpperCase()) .collect(Collectors.toList());
filter
Traverse the data and check and filter the elements
// Filter data with length greater than 1 in string collection List<String> collect = Stream.of("a", "1abc", "abc1") .filter(value -> value.length() > 1) .collect(Collectors.toList());
flatMap
You can replace values with streams, and then connect multiple streams into one Stream
List<Integer> collect = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)) .flatMap(numbers -> numbers.stream()) .collect(Collectors.toList());
Max,Min
public class Track { private String name; private int length; public Track(String name, int length) { this.name = name; this.length = length; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } public void setLength(int length) { this.length = length; } @Override public String toString() { return "Track{" + "name='" + name + '\'' + ", length=" + length + '}'; } }
List<Track> tracks = Arrays.asList(new Track("Bakal", 524), new Track("Violets for Your Furs", 378), new Track("Time Was", 451)); Track shortestTrack = tracks.stream() .min(Comparator.comparing(track -> track.getLength())).get();
reduce
You can generate a value from a set of values. The count, min and max methods used in the above example are included in the standard library because they are commonly used. In fact, these methods are all reduce operations
// Get the accumulated value. The first parameter of reduce is the initial value Integer count = Stream.of(1, 2, 3) .reduce(0, (acc, element) -> acc + element); System.out.println(count); // Expand reduce operation BinaryOperator<Integer> accumulator = (acc, element) -> acc + element; Integer count = accumulator.apply(accumulator.apply(accumulator.apply(0, 1), 2), 3);