Stream Data Stream in Java 8 and java8Stream data Stream
Filter repeated Elements
The Stream interface supports the distinct method, which returns a Stream of elements (implemented based on the hashCode and equals methods of the elements generated by the Stream.
For example, the following code filters out all the even numbers in the list and ensures that there are no duplicates.
List <Dish> dishes = Dish. menu. stream (). filter (Dish: isVegetarian). collect (Collectors. toList (); skip the specified number of elements
Stream supports the skip (n) method and returns a Stream that discards the first n elements. If there are less than n elements in the stream, an empty stream is returned. Limit (n) and skip (n) are complementary.
List <Dish> dishSkip = Dish. menu. stream (). filter (d-> d. getCalories ()> 300 ). skip (2) // removes the first two elements from the compliant set and returns the result. collect (Collectors. toList (); dishSkip. forEach (System. out: println); map operation
Stream supports the map method, which accepts a function as a parameter. This function will be applied to each element and be reflected into a new element.
List <String> list = st. skip (0 ). limit (2 ). map (s-> s. toUpperCase ()). collect (Collectors. toList (); element summation List <Integer> numbers = Arrays. asList (3, 4, 5, 1, 2); int sum1 = numbers. stream (). reduce (0, (a, B)-> a + B); System. out. println (sum1); int sum2 = numbers. stream (). reduce (0, Integer: sum); System. out. println (sum2); maximum value int max = numbers. stream (). reduce (0, Integer: max); System. out. println (max); Minimum value // reduce does not accept the initial value, returns an Optional object (considering that the stream does not have any elements) Optional <Integer> min = numbers. stream (). reduce (Integer: min); min. ifPresent (System. out: println );