数据排列组合实现
示例
将以下几组数据 (“01”, “02”),(“A1”, “A2”, “A3”),(“B1”, “B2”),(“D1”, “D3”)排列组合成,如:01:A1:B1:D1
样例数据。
实现
package com.angel.ocean.utils;import lombok.extern.slf4j.Slf4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;@Slf4j
public class CombinationUtil {// 连接符public static String COMMA = ":";/*** 获取元素组合* @param lists* @param index* @return*/public static List<String> getAllCombination(List<List<String>> lists, Integer index) {if(null == index) {index = 0;}List<String> result = new ArrayList<>();generateCombinations(lists, index, new ArrayList<>(), data -> {// 这里处理每个生成的组合result.add(listToString(data));});return result;}/*** list转字符串* @param list* @return*/private static String listToString(List<String> list) {StringBuilder stringBuilder = new StringBuilder();for (String data : list) {stringBuilder.append(data);stringBuilder.append(COMMA);}if(stringBuilder.length() > 0) {stringBuilder.setLength(stringBuilder.length() - 1);}return stringBuilder.toString();}/*** 元素组合* @param lists* @param index* @param current* @param action*/public static void generateCombinations(List<List<String>> lists, int index, List<String> current, Consumer<List<String>> action) {if (index == lists.size()) {// 所有列表都已遍历完毕,处理当前组合action.accept(new ArrayList<>(current));return;}List<String> sublist = lists.get(index);for (String item : sublist) {current.add(item); // 添加当前项到组合中generateCombinations(lists, index + 1, current, action); // 递归处理下一个列表current.remove(current.size() - 1); // 回溯,移除最后添加的项以尝试其他组合}}// Java 8 引入的函数式接口,用于处理生成的组合@FunctionalInterfaceinterface Consumer<T> {void accept(T t);}
}
验证
public static void main(String[] args) {List<List<String>> lists = Arrays.asList(Arrays.asList("01", "02"),Arrays.asList("A1", "A2", "A3"),Arrays.asList("B1", "B2"),Arrays.asList("D1", "D3"));List<String> list = getAllCombination(lists, 0);for (String data : list) {log.info("{}", data);}
}