Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested lists with streams in Java8

I have a list of objects A. Each object A in this list contains list of object B and the object B contains list of Object C. The object C contains an attribute name that i want to use to filter using java 8.

how to write the code below in java 8 using streams to avoid nested loop :

C c1 = null; String name = "name1" for (A a: listOfAObjects) {     for (B b: a.getList()) {         for (C c: b.getPr()) {             if (c.getName().equalsIgnoreCase(name)) {                 c1= c;                 break;             }         }     } } 
like image 818
sk555 Avatar asked Aug 01 '18 09:08

sk555


People also ask

Does Java 8 have streams?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.

Can we have nested List in Java?

List is a pretty commonly used data structure in Java. Sometimes, we may need a nested List structure for some requirements, such as List<List<T>>.

How do I add an element to a java8 stream to an existing List?

We can add elements of a stream to an existing collection by using forEachOrdered() along with a method reference to List#add() . This approach works for sequential and parallel streams, but it does not benefit from concurrency as the method reference passed to forEachOrdered() will always be executed sequentially.

What are two types of streams in Java 8?

What are the two types of Streams offered by java 8? Explanation: Sequential stream and parallel stream are two types of stream provided by java.


1 Answers

You can use two flatMap then a filter then you can pick the first one or if no result return null :

C c1 = listOfAObjects.stream()         .flatMap(a -> a.getList().stream())         .flatMap(b -> b.getPr().stream())         .filter(c -> c.getName().equalsIgnoreCase(name))         .findFirst()         .orElse(null); 
like image 163
YCF_L Avatar answered Oct 09 '22 20:10

YCF_L