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?
Iterate over the List
of List
's and then call contains:
for(List<Integer> list : dar) {
if(list.contains(5)) {
//...
}
}
Or use Stream
s:
boolean five = dar.stream().flatMap(List::stream).anyMatch(e -> e == 5);
//Or:
boolean isFive = dar.stream().anyMatch(e -> e.contains(5));
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With