Java 8: Streams filter() and map() Methods

filter() Method

				
					Stream<T> filter(Predicate<? super T> predicate)
				
			

filter() method is available in the Stream interface. It accepts the predicate functional interface as a parameter.  Based on the predicate function condition it filters out the elements from the collections.

Example for filter() method

Let’s see the example usage of the filter() method:

In the below example, we have created a List<MovieTicket> Collection object and we retrieved the Movie Tickets with class “A” category.

MovieTicket POJO Class:

				
					class MovieTicket{
    int ticketNumber;
    String seatNumber;
    String classType;
    
    public MovieTicket(int ticketNumber, String seatNumber, String classType){
        this.ticketNumber = ticketNumber;
        this.seatNumber = seatNumber;
        this.classType = classType;
    }
    
    public void setTicketNumber(int ticketNumber){
        this.ticketNumber=ticketNumber;
    }
    public int getTicketNumber(){
        return this.ticketNumber;
    }
    
    public void setSeatNumber(String seatNumber){
        this.seatNumber=seatNumber;
    }
    public String getSeatNumber(){
        return this.seatNumber;
    }
    public void setClassType(String classType){
        this.classType=classType;
    }
    public String getClassType(){
        return this.classType;
    }
    
    public String toString(){
        return "ticketNumber="+this.ticketNumber+" seatNumber="+this.seatNumber+" classType="+this.classType;
    }
}
				
			

Below we have created a MovieTicket List object and we applied the stream on tickets object and called filter() method with conditions like this filter(t -> t.getClassType().equals(“A”))  to get all the tickets with all “A” class ticket and collected the list using the collect() method into another list object.

				
					public class FilterExample
{
    public static void main(String[] args) {
        List<MovieTicket> tickets = new ArrayList<>();
        
        tickets.add(new MovieTicket(1001,"P4","A"));
        tickets.add(new MovieTicket(1001,"T8","A"));
        tickets.add(new MovieTicket(1001,"H10","B"));
        tickets.add(new MovieTicket(1001,"K4","B"));
        tickets.add(new MovieTicket(1001,"R4","A"));
        tickets.add(new MovieTicket(1001,"S5","B"));
        tickets.add(new MovieTicket(1001,"M3","A"));
        tickets.add(new MovieTicket(1001,"S4","A"));
        tickets.add(new MovieTicket(1001,"A4","B"));
        
        System.out.println("****All MovieTickets*****");
        System.out.println(tickets);
        
        System.out.println("****Filter Class A tickets*****");
        List<MovieTicket> classATickets=tickets.stream().filter(t -> t.getClassType().equals("A")).collect(Collectors.toList());
        System.out.println(classATickets);
    }
}
				
			

Output:

				
					****All MovieTickets*****
[ticketNumber=1001 seatNumber=P4 classType=A, ticketNumber=1001 seatNumber=T8 classType=A, ticketNumber=1001 seatNumber=H10 classType=B, ticketNumber=1001 seatNumber=K4 classType=B, ticketNumber=1001 seatNumber=R4 classType=A, ticketNumber=1001 seatNumber=S5 classType=B, ticketNumber=1001 seatNumber=M3 classType=A, ticketNumber=1001 seatNumber=S4 classType=A, ticketNumber=1001 seatNumber=A4 classType=B]
****Filter Class A tickets*****
[ticketNumber=1001 seatNumber=P4 classType=A, ticketNumber=1001 seatNumber=T8 classType=A, ticketNumber=1001 seatNumber=R4 classType=A, ticketNumber=1001 seatNumber=M3 classType=A, ticketNumber=1001 seatNumber=S4 classType=A]

				
			

map() Method

				
					<R> Stream<R> map(Function<? super T,? extends R> mapper)
				
			

map() method is available in the Stream interface. It accepts the function functional interface as a parameter and returns the Stream with R type. R type is nothing but generic type.

map() method is used for data transformation of the collection object. For Example: If you have a List collection object and you want to add 5 to every element. This can be achieved by the map() method.

Example 1: Find the length of List of String

In the below example, we have created List<String> and stored all flower names and got the length of each flower name, and stored it in the List<Integer> collection object. This we have done using map(f-> f.length()). As we know map accepts a function interface. and we implemented the apply() method using lambda function f->f.length(). This implementation will be applied on every collection object and returns the integer value because the function interface accepts any generic type object as a parameter and any generic type as a return type.

				
					public class MapStreamExample
{
    public static void main(String[] args) {
        List<String> flowers = Arrays.asList("Rose","Jasmine","Sunflower","Lilly","Hibiscus");
        
        List<Integer> length = flowers.stream().map(f->f.length()).collect(Collectors.toList());
        System.out.println("**Flower Names**");
        System.out.println(flowers);
        System.out.println("**Their Lengths**");
        System.out.println(length);
    }
}
				
			

Output:

				
					**Flower Names**
[Rose, Jasmine, Sunflower, Lilly, Hibiscus]
**Their Lengths**
[4, 7, 9, 5, 8]

				
			

Example 2: Convert name to uppercase

Student POJO Class:

				
					class Student
{
    int id;
    String name;
    
    public Student(int id,String name){
        this.id=id;
        this.name=name;
    }
    
    public void setId(int id){
        this.id=id;
    }
    public int getId(){
        return this.id;
    }
    public void setName(String name){
      this.name=name;
    }
    public String getName(){
        return this.name;
    }
    
    public String toString(){
        return this.id+" "+this.name;
    }
}
				
			

As we know map() method accepts the function interface as a parameter. In the below example we created a temporary object called std for Student object and return it after converting the name to uppercase.

				
					public class MapStreamExample
{
    public static void main(String[] args) {
        List<Student> students=new ArrayList<>();
        students.add(new Student(1,"Charles"));
        students.add(new Student(2,"Anna Marie"));
        students.add(new Student(3,"John"));
        System.out.println("   List of Students   ");
        System.out.println(students);
        
        System.out.println("   List of Students with Name UPPERCASE   ");
        students=students.stream().map(s->{
            Student std = s;
            std.setName(std.getName().toUpperCase());
            return std;
            }).collect(Collectors.toList());
        System.out.println(students);
        
    }
}
				
			

Conclusion

filter() and map() both are powerful stream methods and reduces the code length and increases the readability and this is possible only because of the lambda expression. In the next article, we will see more methods of streams interface.

Java 8 Stream APIs

Java 8: Introduction to Streams API

Java 8 got a brand new API called streams. it makes every developer’s life easy. Stream APIs are used to process the group of data. mostly streams are applied on collection objects but we can use stream with any group

Read More »