Ads by ProfitSence
Close

Java Stream Filter , Sort Examples

Last Updated on Wednesday 5th Oct 2022

Jav Streams

Java Streams API. It allows you to drive away from Imperative Approach to Declarative Approach Programming.

Java Streams

Filter Methods:

  • We Call the actual collection that we need
  • .stream() - this takes you to abstraction
  • You Can ask what you want of that list
  • We have .filter() method
  • We have to collect the result in the brand new list
  • We used the .collect() method
  • It takes Collector.toList()
			
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List < String > lines = Arrays.asList("Adam", "Olivia", "Amelia", "Harry");

        List < String > result = lines.stream()
            .filter(line - > !"Harry".equals(line))
            .collect(Collectors.toList());

        result.forEach(System.out::println);
    }
}

			
	

The Above code returns

			
					  Adam, Olivia, Amelia

			
	

Sort Methods

  • Whenever we use the Declarative approach, we need to do abstraction mode
  • .stream() - this takes you to abstraction
  • We have .sorted() method
  • It takes Comparator.comparing() Comparator Method
  • It takes Comparator.reverseOrder() Reversing Method
  • We have to collect the result in the brand new list
  • We used the .collect() method
  • It takes Collector.toList()
  • If you want to reverse the output.Just add .reversed() method
			
					import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {

        List < String > list = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O");

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

        sortedList.forEach(System.out::println);
    }
}

			
	

It returns the output in reverse order

			
					O
N
M
L
K
J
I
H
G
F
E
D
C
B
A

			
	
  • Streams Api Easy to work with Collections
  • It tunes the performance as well
  • It's Better with a large amount of data
  • It reduced the many lines of codes