Java 8 stream filter with object attribute

Java 8 stream filter with object attribute

The filter() is an intermediate operation that reads the data from a stream and returns a new stream after transforming the data based on the given condition.

Example of Stream Filter():


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

public class Example {

    public static void main(String[] args) {

        List<String> names = Arrays.asList("A","A1","A2","B","B1");

        List<String> ListOfName = names.stream()    // converting the list to stream
                .filter(str -> str.length() > 1)   // filter the stream to create a new stream
                .collect(Collectors.toList());  // collect the final stream and convert it to a List

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

Output:
A1
A2
B1

Example filter With Object class variable:

@Getter
@setter
class Empolyee{
int id;
String name;
}


List<Empolyee> emp = // List of employee object;

List<Empolyee> ListOfEmp = emp .stream()    // converting the list to stream
                .filter(e -> e.getName().equals("ABC"))   // filter the stream to create a new stream
                .collect(Collectors.toList());  // collect the final stream and convert it to a List

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

Stream filter() and map() method in Java

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

public class Example {

    public static void main(String[] args) {

    List<Integer> num = Arrays.asList(1,2,3,4,5,6);
        List<Integer> squares = num.stream()
        .map(n -> n * n)
        .collect(Collectors.toList());
        System.out.println(squares);       

    }

}


Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation