I have written the following method to generate power set using Java 8 map function
public static List<List<Integer>> powerSet(List<Integer> arr){
List<List<Integer>> powerSet = new ArrayList<>();
powerSet.add(new ArrayList<>());
if(arr.size <= 0)
return powerSet;
for(Integer elem:arr) {
powerSet.stream().map(p -> addSubset(powerSet, p, elem)).collect(Collectors.toList());
}
return powerSet;
}
public static List<List<Integer>> addSubset(List<List<Integer>> powerSet, List<Integer> p, int elem){
List<Integer> newSubset = p;
newSubset.add(elem);
powerSet.add(newSubset);
return powerSet;
}
I always get Concurrent Modification exception. How can I modify this code to generate power set of list?
You are modifying a list as you are iterating thru it. A couple of issues here.
powerSet
and the added list per cycle to avoid a CME.List<Integer> list = new ArrayList<>(List.of(20,30,40,50));
List<List<Integer>> ret = powerSet(list);
ret.forEach(System.out::println);
Prints
[]
[20]
[30]
[20, 30]
[40]
[20, 40]
[30, 40]
[20, 30, 40]
[50]
[20, 50]
[30, 50]
[20, 30, 50]
[40, 50]
[20, 40, 50]
[30, 40, 50]
[20, 30, 40, 50]
The modified methods.
public static List<List<Integer>> powerSet(List<Integer> arr) {
List<List<Integer>> powerSet = new ArrayList<>();
powerSet.add(new ArrayList<>());
if (arr.size() <= 0)
return powerSet;
for (Integer elem:arr) {
for (List<Integer> lst : powerSet) { // <-- instead of streams.
powerSet = new ArrayList<>(powerSet); // <-- new copy here
addSubset(powerSet, lst, elem);
}
}
return powerSet;
}
public static void addSubset(
List<List<Integer>> powerSet, List<Integer> p, int elem) {
p = new ArrayList<>(p); // <-- new copy here
p.add(elem);
powerSet.add(p);
}