Java Stream API

[TOC]

Steam in Java8 can be defined as a sequence of elements from a source, and Streams supports aggregation of elements, which are collections and arrays of data that feed a stream, in which we can get the data that we want from the stream

Before we start working with Streams, we should know that the Streams API is a direct Stream operation, so we need to create a Steam first.

At the granularity level, the difference between a Collection and a Stream has to do with the time it takes to calculate things. A Collection is an in-memory data structure in which all the values currently held by the data structure are considered. Each element in the collection must be evaluated before it can be added to the collection. A Stream is conceptually a pipeline in which elements are counted on demand.

This concept brings significant programming advantages. The idea is that users will only extract the values they need from the Stream, and these elements will be generated only when needed (invisible to the user). This is a form of producer-consumer relationship.

In Java, java.util.Stream represents a Stream on which one or more operations can be performed. Stream operations are either intermediate or terminal.

The terminal operation returns a particular type of result and the intermediate operation returns the stream itself, so we can chain multiple methods in a row to perform the operation in multiple steps.

Streams are created on a source, such as java.util.Collection like List or Set. In Map not directly supported, we can create Map keys, values.

Flow operations can be executed sequentially or in parallel. When executed in parallel, it is called a parallel stream

1. Create flow

Here are some ways to create a stream

1.1 the Stream of ()
Public static void main(String[] args) {Stream<Integer> Stream = stream. of(1,2,3,4,5,6,7,8,9);  stream.forEach(p -> System.out.println(p)); }
1.2 Stream. Of (array)

We can generate a stream by introducing an array

Public static void main(String[] args) {Stream<Integer> Stream = stream. of(new Integer[]{1,2,3,4,5,6,7,8,9}); stream.forEach(p -> System.out.println(p)); }
1.3 List. Steam (commonly used)

In our work, we often use a collection to retrieve a stream, with the elements of the stream coming from a List

public static void main(String[] args)
     {
         List<Integer> list = new ArrayList<Integer>();
 
         for(int i = 1; i< 10; i++){
             list.add(i);
         }
 
         Stream<Integer> stream = list.stream();
         stream.forEach(p -> System.out.println(p));
     }
Generate () or stream.iterate ()

// In the code below, we create a stream from the given element, but we are only limiting to getting 20, so we limit it with limit

 public static void main(String[] args)
     {
         Stream<Integer> randomNumbers = Stream
             .generate(() -> (new Random()).nextInt(100));
 
         randomNumbers.limit(20)
              .forEach(System.out::println);
     }

1.5 string string stream

public static void main(String[] args)
     {
        IntStream stream = "12345_abcdefg".chars();
        stream.forEach(p -> System.out.println(p));
         
    //OR
         
        Stream<String> stream = Stream.of("A$B$C".split("\\$"));
        stream.forEach(p -> System.out.println(p));
     

1.6 Stream. Builder ()

Create a builder by creating a Builder method, which also generates the stream

Stream<Object> name = Stream.builder().add("name").build();

2. A Stream Collector

After performing the middleware operations on the elements in the stream, we can use the flow collector method to collect the processed elements again into a collection

2.1 Collect the elements in a stream into a collection

In the given example, we first create a stream on integers 1 through 10. Then we process the stream elements to find all the even numbers. Finally, all the even numbers are collected into a set

 public static void main(String[] args)
     {
         List<Integer> list = new ArrayList<Integer>();
 
         for(int i = 1; i< 10; i++){
             list.add(i);
         }
 
         Stream<Integer> stream = list.stream();
         List<Integer> evenNumbersList = stream.filter(i -> i%2 == 0)
                                                .collect(Collectors.toList());
         System.out.print(evenNumbersList);
     }
2.2 Collect the stream elements into an array

As in the previous example, we gathered even numbers into an array this time

List<Integer> result = new ArrayList<>();
        for (Integer x : list) {
            if (x % 2 == 0) {
                result.add(x);
            }
        }

Integer[] evenNumbersArr = list.stream().filter(x -> x% 2 == 0).toArray(Integer[]::new);


Of course, a flow collector can be collected not only from lists, but also sets, maps, etc., which can be implemented through calls to the Collectors

3. The flow operation

There are two kinds of operations on streams
Intermediate flow operationMake and
Terminal operation

  • The intermediate stream operation returns a Steam stream after the operation,
  • The data in 6 is processed directly after the terminal operation, with no return value

    List<String> memberNames = new ArrayList<>(); memberNames.add("Amitabh"); memberNames.add("Shekhar"); memberNames.add("Aman"); memberNames.add("Rahul"); memberNames.add("Shahrukh"); memberNames.add("Salman"); memberNames.add("Yana"); memberNames.add("Lokesh");
3.1.1 Stream.Filter
The filter operation accepts A Predicate-type method and returns A Steam stream that meets Predicate's requirements, such as the city starting with A from the above collection
memberNames.stream().filter((s) -> s.startsWith("A"))                    .forEach(System.out::println);
3.1.2 Stream.Map

I think of the map operation as a conversion or mapping operation, where we convert all lowercase characters in a collection to uppercase characters

memberNames.stream().filter((s) -> s.startsWith("A"))                    .map(String::toUpperCase)                    .forEach(System.out::println);
3.1.3 Stream.sorted

The sort interface allows you to sort the elements of a collection directly. Before Java 8 we had to sort the elements of a list, which was a bit more complicated, using sort, using anonymous inner classes in Compare, which was a bit more complicated to write

memberNames.sort(new Comparator<String>() { @Override public int compare(String o1, String o2) { return 0; }});

But now with Java 8, we can sort in a different way

memberNames.stream().sorted()                    .map(String::toUpperCase)                    .forEach(System.out::println);

The default is to sort in the forward direction. If you want to sort in the reverse direction, you can use the reverse method to change the order

3.2 Terminal operation

The terminal operation returns the result of the terminal operation,

3.2.1 Stream. Foreach

Foreach is a function that traverses iterations

memberNames.forEach(System.out::println);
3.2.2 collect collect

Collect is a collection method that retrieves consistent data from a Stream and stores it in a collection

List<String> memNamesInUppercase = memberNames.stream().sorted()                            .map(String::toUpperCase)                            .collect(Collectors.toList());         System.out.print(memNamesInUppercase);
3.2.3 match match

Match is my general term for a method of the Match class, which is similar to Filter, but slightly more powerful and has more methods

TrueBoolean matchedResult = memberNames. Stream (). AnyMatch ((s) -> s.startsWith("A")); System.out.println(matchedResult); // return trueMatchedResult = memberNames. Stream ().allMatch((s) -> s.tartsWith ("A")); System.out.println(matchedResult); // return trueMatchedResult = memberNames. Stream (). NoneMatch ((s) -> s.tartsWith ("A")); System.out.println(matchedResult);
4.2.4. Stream. The count ()

A terminal operation that counts, returning a long

long totalMatched = memberNames.stream()    .filter((s) -> s.startsWith("A"))    .count(); System.out.println(totalMatched);
4.2.5. Stream. The reduce ()

To compute a value in a stream to a final result based on the specified computation model.

There is a blogger article that does a particularly good job on this approach, taking a look at Java8 Reduce

The summary documents the common stream operation methods

In the middle of operation

  • filter
  • map
  • distinct
  • sorted
  • peek
  • limit
  • skip

Terminal operation

  • foreach
  • toArray
  • reduce
  • foreachOrdered
  • min
  • max
  • count
  • anyMatch
  • collect
  • Findfirst etc.