Stream API

Stream API in Java:

The Stream API in Java is a powerful tool introduced in Java 8 for processing collections of data in a functional and declarative way. It allows developers to perform various operations on collections, such as filtering, mapping, sorting, and reducing, using functional programming concepts.

Importance of Stream API:

  • Stream API enables developers to write more concise and readable code by using functional-style operations on collections.
  • It promotes efficient and parallel processing of data by automatically handling the internal iteration and providing optimizations.
  • Stream API encourages a more declarative programming style, where the focus is on what operations need to be performed rather than how they should be implemented.

Examples:

  1. Filtering even numbers from a list:
  2. 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());
  3. Mapping names to uppercase:
  4. List<String> names = Arrays.asList("John", "Jane", "Tom");
    List<String> upperCaseNames = names.stream()
                                        .map(String::toUpperCase)
                                        .collect(Collectors.toList());
  5. Sorting a list of integers in descending order:
  6. List<Integer> numbers = Arrays.asList(5, 3, 8, 2, 1);
    List<Integer> sortedNumbers = numbers.stream()
                                             .sorted(Comparator.reverseOrder())
                                             .collect(Collectors.toList());
  7. Calculating the sum of all elements in a list:
  8. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
    int sum = numbers.stream()
                    .reduce(0, Integer::sum);
  9. Counting the number of names starting with "J":
  10. List<String> names = Arrays.asList("John", "Jane", "Tom", "Jessica");
    long count = names.stream()
                     .filter(name -> name.startsWith("J"))
                     .count();

In the above examples, the Stream API is used to perform various operations on collections such as filtering, mapping, sorting, reducing, and counting. These operations are chained together using fluent syntax, resulting in concise and readable code. The examples demonstrate the power and flexibility of the Stream API in simplifying data processing tasks.

How to create Stram Api and what are its type ? Click Here

How to use Stram Api in Java? Click Here

What is Parallel processing Stram in Java ? Click Here

Post a Comment

Previous Post Next Post