Extract list from list of lists
7 replies
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
0
source to share
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);
0
source to share
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
0
source to share