Java 获取 List 中元素的所有子集

原创转载请注明出处:https://www.cnblogs.com/agilestyle/p/17135599.html

 

Maven Dependency

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.22</version>
</dependency>

 

SRC

package org.fool.test;

import cn.hutool.core.math.MathUtil;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class SubsetTest {
    public static void main(String[] args) {
        List<String> dataList = Lists.newArrayList("2", "3", "5");

        List<String[]> resultList = subset(dataList.toArray(String[]::new));

        resultList.forEach(p -> {
            List<String> collect = Arrays.stream(p).collect(Collectors.toList());
            System.out.println(collect);
        });
    }

    public static List<String[]> subset(String[] datas) {
        List<String[]> resultList = new ArrayList<>();

        for (int i = 0; i <= datas.length; i++) {
            List<String[]> result = MathUtil.combinationSelect(datas, i);
            resultList.addAll(result);
        }

        return resultList;
    }
}

 

Console Output

[]
[2]
[3]
[5]
[2, 3]
[2, 5]
[3, 5]
[2, 3, 5]

 

posted @ 2023-02-19 21:01  李白与酒  阅读(442)  评论(0编辑  收藏  举报