Working with a List of Lists in Java

How to find an element in a list of lists

Iterate over the List of List's and then call contains:

for(List<Integer> list : dar) {
if(list.contains(5)) {
//...
}
}

Or use Streams:

boolean five = dar.stream().flatMap(List::stream).anyMatch(e -> e == 5);
//Or:
boolean isFive = dar.stream().anyMatch(e -> e.contains(5));

List of Lists of Lists

All the other answers are technically correct, but IMHO if you implement a rough List of Lists of Lists you are not treating your data at the right level of abstraction. For example I am pretty sure that a List of Lists already means "something" in your business domain. Encapsulate this "something" in another object so you can just have a List<Something> instead of a difficult to use and maintain List<List<List<Object>>>.

JAVA, list of lists

Objects are always passed as references in Java.

When you add singleList to listOfLists, you are in fact adding a reference to singleList. Since you've added it 3 times, you got the current value of singleList, repeated 3 times.

The "previous values" of singleList are stored nowhere, so A B C and D E F are lost.

You need to make a copy of your list, by using new ArrayList<String>(singleList). Then, add this copy to listOfLists.

Extract a list from list of lists

Do it like this:

List<List<Integer>> permutationS = new ArrayList<>();

// list initialization here

int i = 5; // the Integer you are searching for

for(List<Integer> innerList : permutationS) {
if(innerList.contains(i)) {
// found, do something with innerList
}
}

List of lists and Java 8

rList.stream().map(R::getP).flatMap(List::stream).forEach(result::addAll);

would work if you didn't use flatMap (since addAll requires a Collection, but flatMap transforms your Stream<List<P>> to a Stream<P>.

This would work:

rList.stream().map(R::getP).forEach(result::addAll);

With flatMap it should be:

rList.stream().map(R::getP).flatMap(List::stream).forEach(result::add);

That said, the correct way is to use collect:

List<P> result = rList.stream()
.map(R::getP)
.flatMap(List::stream)
.collect(Collectors.toList());

or

List<P> result = rList.stream()
.flatMap(r -> r.getP().stream())
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit