Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 Extract multiple fields from a class object using streams

I have a List of class A objects with multiple fields including number1 & number2 apart from various others.

I want to extract all the unique number1 & number2 values from the List<A> via java 8 Streams.

The map function helps me get only 1 field like below:

list.stream().map(A::getNumber1);

And after the above code gets executed, there is no way to extract number2. How can I do this?

like image 317
Pankaj Singhal Avatar asked Jan 24 '18 07:01

Pankaj Singhal


1 Answers

You can extract both by using flatMap:

list.stream().flatMap(a -> Stream.of(a.getNumber1(),a.getNumber2())).distinct()...
like image 200
Eran Avatar answered Oct 19 '22 13:10

Eran