Extract list from list of lists
I have a list of lists in java.
static ArrayList<List> permutationS = new ArrayList<List>();
The inner list is an ArrayList of integers.
List<Integer> innerList = new ArrayList<Integer>();
Now I want to select innerList if it contains a specific integer. How can I achieve this?
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
}
}
As I don't know which version of Java you are using, I suggest looping through it as
List<List<Integer>> Permutation_S = new ArrayList<List<Integer>>();
for(List<Integer> listInList: Permutation_S){
for(Integer integerValue: listInList){
if(integerValue == 2 /*your desired value*/){
//DO SOMETHING
}
}
}
You can of course use streams if you are on Java 8 or higher
Solution with stream
:
int x = 3; // the number to be looked
List<Integer> selectedInnerList = permutationS.stream()
.filter(s -> s.contains(x))
.findFirst()
.get();
Note that it findFirst()
returns an optional object, so it get()
throws an exception if there is no such element
What about:
public List getList(Object value) {
for (List inner : Permutation_S) {
if (inner.contains(value))
return inner;
}
}
One solution would be to remove all List<Integer>
that do not contain a specific integer (e.g. 10):
permutationS.removeIf(list -> !list.contains(10));
Another solution would be to use streams and filtering to do it:
permutationS.stream()
.filter(list -> list.contains(10))
.collect(Collectors.toList());
If you're looking for just one List<Integer>
, you can use the following:
List<Integer> newList = permutationS.parallelStream()
.filter(list -> list.contains(10))
.findAny()
.orElseGet(ArrayList::new);
Maybe with a structure like this?
for (List<Integer> lists : permutationS) {
for(Integer integers : lists){
//Your tests
}
}
This will allow you to get a list that contains the value you want, and if none of the inner lists contain it, it will return a new empty list:
int val = 10;
List<Integer> innerList = permutationS.stream() //iterate over inner lists
.filter(list -> list.contains(val)) //keep one which contains the value
.findAny() //keep only one if exists
.orElse(new ArrayList<>()); // if no-one return new List
Example:
permutationS.add(Arrays.asList(0, 6, 13, 14));
permutationS.add(Arrays.asList(1, 10, 11, 18, 6, 78, 79, 9));
permutationS.add(Arrays.asList(2, 22, 4, 20));
List<Integer> innerList = permutationS.stream().filter(list -> list.contains(10))
.findAny().orElse(new ArrayList<>());
innerList.size(); // = 8
List<Integer> innerList2 = permutationS.stream().filter(list -> list.contains(34))
.findAny().orElse(new ArrayList<>());
innnerList2.size(); // = 0