Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find an element in a list of lists

Tags:

java

I have the following list of lists List<List<Integer>> dar = new ArrayList<List<Integer>>();:

[[0], [1, 2, 0], [2, 1, 0], [5, 0]]

I want to check whether the integer 5 is in any of the lists. If I use if(dar.contains(5)), it will return false.

What can I do to check whether an integer exists in any of the lists?

like image 280
Adam Amin Avatar asked Oct 16 '25 04:10

Adam Amin


2 Answers

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));
like image 101
GBlodgett Avatar answered Oct 18 '25 16:10

GBlodgett


You have List of Lists. To search any value, you need nested loops.

public void contains(Integer x){
    for (int i= 0; i < dar.size(); i++){
        List<Integer> list = dar.get(i);
        for(int j= 0; j < list.size(); j++){
             if(x == list.get(j)) return true; //will handle both null cases
             if( x != null && x.equals(list.get(j)) return true;
        }
    }
}
like image 30
nits.kk Avatar answered Oct 18 '25 17:10

nits.kk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!