cs notebook2
  • Introduction
  • functional interface
  • Lambda expressions
  • Stream
  • Method and Constructor Reference
  • Collectors
  • exe
  • Interface Changes
Powered by GitBook
On this page
  • 1. Collections VS Stream
  • 2. Deeper Look at Streams
  • 3. forEach & forEachOrdered
  • 4. Stream.peek
  • 5. Stream.skip
  • 6. stream().map()
  • 7. Streams filter()
  • eg2 The equivalent example in Java 8, use

Was this helpful?

Stream

1. Collections VS Stream

  • Collections are in-memory data structures which hold elements within it. Each element in the collection is computed before it actually becomes a part of that collections. On the other hand Streams are fixed data structures which computers the elements on-demand basis.

  • The Java 8 Streams can be seen as lazily constructed Collections, where the values are computed when user demands for it. Actual Collections behave absolutely opposite to it and they are set of eagerly computed values(no matter if the user demands for a particular value or not).

2. Deeper Look at Streams

Just like functional programming languages, Streams support Aggregate Operations. The common aggregate operations are filter, map, reduce, find, match, sort. These operations can be executed in series or in parallel.

The Streams also support Pipelining and Internal Iterations. The Java 8 Streams are designed in such a way that most of its stream operations returns streams only. Java 8 Stream operations has methods like foreach, map, filter, etc.

3. forEach & forEachOrdered

forEach() method accepts Consumer as an argument and that consumer is applied to each element of the stream. For example we can create a consumer to print the stream element and use it with forEach() method.

forEachOrdered() method does the same thing but in the encounter order of the stream.

Stream.of("AAA","BBB","CCC").forEach(s->System.out.println(s));

output:

AAA
BBB
CCC

4. Stream.peek

peek() is an intermediate operation. It returns a new stream which consists all the elements of stream after applying the Consumer.

This method takes one Consumer as an argument, this consumer accepts one parameter T as an input argument and return one stream of parameter T as a return value. The main purpose of this method is to support debugging, when you want to see(peek) the elements as they flow through the certain point in a stream pipeline. You can achieve this by using a Consumer Interface with System.out.println in it.

5. Stream.skip

skip() is a method that skips given number of element from the stream object from start.

List<String> list = Arrays.asList("AA","BB","CC","DD");
list.stream().skip(2).forEach(s->System.out.println(s));

output:

CC
DD

6. stream().map()

To convert elements of a Stream by applying a special function to them and to collect these new elements into a Stream, we can use the map() method:

eg:

list.stream().map(String::toUpperCase);
list.stream().map(str->str.length()).forEach(System.out::println);

7. Streams filter()

eg

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NowJava8 {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("spring", "node", "mkyong");

        List<String> result = lines.stream()                // convert list to stream
                .filter(line -> !"mkyong".equals(line))     // we dont like mkyong
                .collect(Collectors.toList());              // collect the output and convert streams to a List

        result.forEach(System.out::println);                //output : spring, node

    }

}

eg2 The equivalent example in Java 8, use

stream.filter() to filter a List, and .findAny(). or Else (null) to return an object conditional.

import java.util.Arrays;
import java.util.List;

public class NowJava8 {

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()                        // Convert to steam
                .filter(x -> "jack".equals(x.getName()))        // we want "jack" only
                .findAny()                                      // If 'findAny' then return found
                .orElse(null);                                  // If not found, return null

        System.out.println(result1);

        Person result2 = persons.stream()
                .filter(x -> "ahmook".equals(x.getName()))
                .findAny()
                .orElse(null);

        System.out.println(result2);

    }

}

8. Intermediate Operations:

1. map: The map method is used to map the items in the collection to other objects according to the Predicate passed as argument.

List<Integer> num = Arrays.asList(2,3,4);
List<Integer> square = num.stream().map(x->x*x).collect(Collections.toList());

2. filter: The filter method is used to select elements as per the Predicate passed as argument.

List<String> names = Arrays.asList("Snow", "Sand", "Wind");
List<String> result = names.stream().filter(s->s.startsWith("S")).collect(Collectors.toList());

3. sorted: The sorted method is used to sort the stream

List<String> names = Arrays.asList("Snow", "Sand", "Wind");
List<String> result = names.stream().sorted().collect(Collectors.toList());

9. Terminal Operations:

Java-8 Stream terminal operations produces a non-stream, result such as primitive value, a collection or no value at all. Terminal operations are typically preceded by intermediate operations which return another Stream which allows operations to be connected in a form of a query.

Here is the list of all Stream terminal operations:

  • toArray(): converts a stream into an array.

  • collect()

  • count()

  • reduce()

  • forEach()

  • forEachOrdered()

  • min()

  • max()

  • anyMatch()

  • allMatch()

  • noneMatch()

  • findAny()

  • findFirst()

1. collect: The collect method is used to return the result of the intermediate operations performed on the stream.

eg:

List<String> collectorCollection = productList.stream().map(Product::getName).collect(Collectors.toList());

2. forEach: The forEach method is used to iterate through every element of the stream.

3. reduce: The reduce method is used to reduce the elements of a stream to a single value.

 List<Integer> num = Arrays.asList(2, 3, 4, 5, 6,7,8,-4,1);
 int even = num.stream().filter(x->x%2==0).reduce(0,(ans,i)->ans+i);
        System.out.println(even);
PreviousLambda expressionsNextMethod and Constructor Reference

Last updated 5 years ago

Was this helpful?

https://www.mkyong.com/java8/java-8-streams-filter-examples/