DEV Community


Java Streams filter, distinct and map

sanjay shivanna
Keep learning
・1 min read

Simple example to illustrate using Java stream with filter,distinct and map.

 public static void main(String[] args) {
        Person lokesh = new Person(1, "Lokesh", "Gupta");
        Person brian = new Person(2, "Brian", "Clooney");
        Person alex = new Person(3, "Alex", "Kolen");
        Person ram = new Person(1, "Ram", "Mani");
        Person rahim = new Person(2, "Rahim", "sab");
        Person jhon = new Person(3, "Jhon", "son");

        List<String> personList = Arrays.asList("Lokesh", "Alex", "Peter");

        Collection<Person> list = Arrays.asList(lokesh, brian, alex, lokesh, brian, lokesh, ram, rahim, jhon);
        // Filter out fnames and then get distinct lastNames
        List<String> listWithLastName =
                .filter(person -> !personList.contains(person.getFname()))
                .map(person -> person.getLname())

        // Out put - [Clooney, Mani, sab, son]

After running above program you will see output like below
[Clooney, Mani, sab, son]

create pojo person class with the fields mentioned above

The example above is referred from and modified to explain filter,distinct and collect.

Discussion (0)

Forem Open with the Forem app