DEV Community

sanjay shivanna
sanjay shivanna

Posted on

Java Streams filter, distinct and map

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 = list.stream()
                .filter(person -> !personList.contains(person.getFname()))
                .distinct()
                .map(person -> person.getLname())
                .collect(Collectors.toList());

        // Out put - [Clooney, Mani, sab, son]
        System.out.println(listWithLastName);
    }

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 https://howtodoinjava.com/java8/java-stream-distinct-examples/ and modified to explain filter,distinct and collect.

Top comments (0)