Java Stream Api

Posted By :Deepak Singh Chauhan |25th November 2019


Why We Need Java Stream API?
 

The Java Stream API provides a functional way to handle object collections. Java Stream API was accessorial in Java 8 at the side of many alternative programming options. It is a component that is capable of internal iteration of its elements which means it can iterate its elements itself whereas when we are using the Java Collections iteration features i.e a Java Iterator or the Java for-each loop used with a Java Iterable. we have to implement the iteration of the elements ourselves.


Creating Java Streams:
 

There are several ways we can create a Java stream from a collection and array.

1. We can use Stream.of () to create a stream from a similar type of data.

Stream<Integer> stream = Stream.of(1,2,3,4);

2. We can use Stream.of() with an array of Objects to return the stream.

Stream<Integer> stream = Stream.of(new Integer[]{1,2,3,4})

3. We can use the Collection stream() to create the sequential stream and parallel streams() to create a parallel stream.

List<Integer> myList = new ArrayList<>();
for(int i=0; i<100; i++) myList.add(i);
        
//sequential stream
Stream<Integer> sequentialStream = myList.stream();
        
//parallel stream
Stream<Integer> parallelStream = myList.parallelStream();

 

Java Stream Intermediate Operations:
 

1. Stream filter () 

The Java Stream filter() can be used to filter out elements from a Java Stream. We can use filter() method to test stream elements for a condition and generate the filtered list.

Example-:

List<Integer> myList = new ArrayList<>();
for(int i=0; i<100; i++) myList.add(i);
Stream<Integer> sequentialStream = myList.stream();

Stream<Integer> highNums = sequentialStream.filter(p -> p < 5); //filter numbers less than 5
System.out.print("Nums less than 5=");
highNums.forEach(p -> System.out.print(p+" "));
//prints "Nums less than="4,3,2,1,0

2. Stream map ()

The Java Stream map() method converts (maps) an element to another object. For example, if you have a list of strings, you can convert each string to lowercase, uppercase or substring of the original string, or fully convert to another string.

 Example:

Stream<String> names = Stream.of("aBc", "d", "ef");
System.out.println(names.map(s -> {
        return s.toUpperCase();
    }).collect(Collectors.toList()));
//prints [ABC, D, EF]

3. Stream sorted () 

Java Stream sorted () is used to sort the stream elements by passing the Comparator argument.

 Example:

Stream<String> testingString1 = Stream.of("aBc", "d", "ef", "123456");
List<String> reverseSorted = testingString1.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
System.out.println(reverseSorted); // [ef, d, aBc, 123456]

Stream<String> testingString2 = Stream.of("aBc", "d", "ef", "123456");
List<String> naturalSorted = testingString2.sorted().collect(Collectors.toList());
System.out.println(naturalSorted); //[123456, aBc, d, ef]

4. Stream flatMap ()

The Java Stream flatMap () method assigns a single item to multiple items. The idea is to "flatten" each element from a complex structure consisting of multiple internal elements to a "flat" stream consisting only of these internal elements.

Example:

Stream<List<String>> namesOriginalList = Stream.of(
    Arrays.asList("Rahul"), 
    Arrays.asList("REETA", "Kailas"),
    Arrays.asList("Akash"));
//flat the stream from List<String> to String stream
Stream<String> flatStream = namesOriginalList
    .flatMap(strList -> strList.stream());

flatStream.forEach(System.out::println);

Thank You

 


About Author

Deepak Singh Chauhan

Deepak is a bright Java Developer, having good skills in Java, Servlet and Spring MVC Framework. His hobbies are travel and explore new places and learning about new technologies .

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us