DEV Community

sanjay shivanna
sanjay shivanna

Posted on

1

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.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay