Quick Note on Java Streams

Quick Note on Java Streams

Java Streams is a powerful tool that was introduced in Java 8. It is used to manipulate the collection of objects in a functional way.

Streams enable developers to perform complex data processing operations on collections with minimal code and better readability.

Here are some key points about Java Streams:

1. Sequence of Elements: A stream is a sequence of elements that supports various operations to perform computations on those elements. Streams can be created from collections, arrays, or by using stream-generating methods.

2. Functional Operations: Streams support functional-style operations such as map, filter, reduce, and forEach. These operations allow developers to express common data processing patterns in a concise and declarative manner.

3. Lazy Evaluation: Stream operations are typically lazy, meaning they do not process the entire data set at once. Instead, elements are processed on-demand as needed, which can improve performance by avoiding unnecessary computations.

4. Parallel Execution: Streams can take advantage of multi-core processors by performing operations in parallel. Parallel streams are created using the parallel() method, and the stream API automatically handles the parallelization of operations.

5. Immutable Data: Streams do not modify the original data source. Instead, they produce new streams with modified data. This ensures that the original data remains unchanged, which is important for functional programming principles.

6. Integration with Collections: Streams seamlessly integrate with existing Java collections, providing methods such as stream(), parallelStream(), and collectors for easy conversion between collections and streams.

7. Optional: Streams often return Optional values, which indicate that a value may or may not be present. This helps to handle scenarios where a computation may result in a null value without explicitly throwing NullPointerExceptions.

Below is a comprehensive list of all the methods provided by the Java Streams API:

Intermediate Operations:

1- filter(Predicate<? super T> predicate): Returns a stream consisting of the elements that match the given predicate.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");

// Filter names starting with 'A'
List<String> filteredNames = names.stream()
                                .filter(name -> name.startsWith("A"))
                                .collect(Collectors.toList());
System.out.println(filteredNames); 

// Output: [Alice]        

2- map(Function<? super T, ? extends R> mapper): Returns a stream consisting of the results of applying the given function to the elements of this stream.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Map each number to its square

List<Integer> squares = numbers.stream()

                              .map(n -> n * n)

                              .collect(Collectors.toList());

System.out.println(squares);

// Output: [1, 4, 9, 16, 25]        


3- flatMap(Function<? super T, ? extends Stream<? extends R>> mapper): Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

List<List<Integer>> nestedList = Arrays.asList(
  Arrays.asList(1, 2, 3),

            Arrays.asList(4, 5, 6),

            Arrays.asList(7, 8, 9)

        );

        List<Integer> flattenedList = nestedList.stream()

                                                .flatMap(List::stream) // Flatten the nested lists

                                                .collect(Collectors.toList());

        System.out.println(flattenedList);

        

        // Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]        

? ? ? ? ?

4- distinct(): Returns a stream consisting of the distinct elements of this stream.

List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 3, 4, 5, 5);
// Get distinct numbers

List<Integer> distinctNumbers = numbers.stream()

                                       .distinct()

                                       .collect(Collectors.toList());

System.out.println(distinctNumbers); 

// Output: [1, 2, 3, 4, 5]        


5- sorted(): Returns a stream consisting of the elements of this stream, sorted according to natural order.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Sort names in ascending order

List<String> sortedNames = names.stream()

                               .sorted()

                               .collect(Collectors.toList());

System.out.println(sortedNames); 

// Output: [Alice, Bob, Charlie, David]        


6- sorted(Comparator<? super T> comparator): Returns a stream consisting of the elements of this stream, sorted according to the provided comparator.

List<String> sortedNames = names.stream()  .sorted(Comparator.reverseOrder()).collect(Collectors.toList());

// Output: [David, Charlie, Bob, Alice]        

? ? ? ? ? ? ? ? ? ? ? ? ? ? ?

7- peek(Consumer<? super T> action): Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
 List<Integer> processedNumbers = numbers.stream()
.peek(System.out::println) // Print each number
.map(n -> n * n) // Square each number
.collect(Collectors.toList());

System.out.println("Processed numbers: " + processedNumbers);        

Terminal Operations:

1- forEach(Consumer<? super T> action): Performs an action for each element of this stream.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Print each name
names.stream().forEach(System.out::println);

// Output:
// Alice
// Bob
// Charlie
// David        


2- forEachOrdered(Consumer<? super T> action): Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.

3- toArray(): Returns an array containing the elements of this stream.

4- reduce(T identity, BinaryOperator<T> accumulator): Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Calculate the sum of all numbers
int sum = numbers.stream().reduce(0, Integer::sum);

System.out.println(sum); 

// Output: 15        


5- reduce(BinaryOperator<T> accumulator): Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any.

6- reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner): Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions.

7- collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner): Performs a mutable reduction operation on the elements of this stream using a Collector.

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Collect names into a HashSet

Set<String> uniqueNames = names.stream().collect(Collectors.toSet());

System.out.println(uniqueNames); 

// Output: [Bob, Charlie, Alice, David]        


8- min(Comparator<? super T> comparator): Returns the minimum element of this stream according to the provided Comparator.

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);
  // Find the minimum element
Optional<Integer> min = numbers.stream().min(Integer::compareTo);

min.ifPresent(System.out::println); 

// Output: 1        

? ? ?

9- max(Comparator<? super T> comparator): Returns the maximum element of this stream according to the provided Comparator.

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);
  // Find the maximum element
Optional<Integer> max = numbers.stream().max(Integer::compareTo);

max.ifPresent(System.out::println); 

// Output: 9        

? ? ?

10- count(): Returns the count of elements in this stream.

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);
// Count the elements in the stream
long count = numbers.stream().count();

System.out.println("Count: " + count); 

// Output: 8        

? ? ? ?

11- anyMatch(Predicate<? super T> predicate): Returns whether any elements of this stream match the provided predicate.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Check if any number is even
boolean anyEven = numbers.stream().anyMatch(n -> n % 2 == 0);

System.out.println(anyEven); 

// Output: true        


12- allMatch(Predicate<? super T> predicate): Returns whether all elements of this stream match the provided predicate.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Check if all elements are even

boolean allEven = numbers.stream().allMatch(num -> num % 2 == 0);

// Output: false (not all elements are even)        


13- noneMatch(Predicate<? super T> predicate): Returns whether no elements of this stream match the provided predicate.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Check if no element is negative
boolean noneNegative = numbers.stream().noneMatch(num -> num < 0);

// Output: true (no element is negative)        


14- findFirst(): Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Find the first even number

Optional<Integer> firstEven = numbers.stream().filter(num -> num % 2 == 0).findFirst();

// Output: Optional[2] (first even number)        


15- findAny(): Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty.

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
// Find any even number

Optional<Integer> anyEven = numbers.stream().filter(num -> num % 2 == 0).findAny();

// Output: Optional[2] (any even number)        


**************Happy Learning*****************

要查看或添加评论,请登录

社区洞察

其他会员也浏览了