Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
394 views
in Technique[技术] by (71.8m points)

powerset - Java 8 - Generate power set of list

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?

question from:https://stackoverflow.com/questions/65930095/java-8-generate-power-set-of-list

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are modifying a list as you are iterating thru it. A couple of issues here.

  • don't use streams. It isn't appropriate or helpful.
  • make a copy of 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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...