java—将Map中的多个集合合并为唯一的字符串

9bfwbjaz  于 2021-07-07  发布在  Java
关注(0)|答案(2)|浏览(391)

我需要把所有的字符串组合在一个数组的所有集合中 Map<String, Set<String>> 唯一字符串的组合。集合的数量可以变化,集合中的字符串数量也可以变化。
我脑子里想不起来。示例代码为:

// Create a map
Map<String, Set<String>> map = new HashMap<String, Set<String>>();

// Create setA
Set<String> setA = new HashSet<String>();
setA.add("A");
setA.add("B");
// There could be more (or less) values in setA

// Create setB
Set<String> setB = new HashSet<String>();
setB.add("X");
setB.add("Y");
// There could be more (or less) values in setB

// Create setC
Set<String> setC = new HashSet<String>();
setC.add("1");
setC.add("2");
// There could be more (or less) values in setC

// Add sets to map
map.put("a", setA);
map.put("b", setB);
map.put("c", setC);
// There could be more sets to add to the map
/*
 * Combine each value from each set in the
 * map {a=[A, B], b=[X, Y], c=[1, 2]} to
 * unique strings. Output should be:
 * A X 1
 * A X 2
 * A Y 1
 * A Y 2
 * B X 1
 * B X 2
 * B Y 1
 * B Y 2
 * ... more combinations if there are more values
 */
gdx19jrr

gdx19jrr1#

最后,我使用guava库创建了笛卡尔积。使用方便,性能良好。

agyaoht7

agyaoht72#

你可以用这个方法 Stream.reduce(accumulator) 为此目的:

Set<Set<String>> sets = new LinkedHashSet<>(List.of(
        new LinkedHashSet<>(List.of("A", "B")),
        new LinkedHashSet<>(List.of("X", "Y")),
        new LinkedHashSet<>(List.of("1", "2"))));
Set<String> set = sets.stream()
        .reduce((s1, s2) -> s1.stream().flatMap(e1 ->
                s2.stream().map(e2 -> e1 + ":" + e2))
                .collect(Collectors.toCollection(LinkedHashSet::new)))
        .orElse(Set.of(""));
set.forEach(System.out::println);
// A:X:1
// A:X:2
// A:Y:1
// A:Y:2
// B:X:1
// B:X:2
// B:Y:1
// B:Y:2

相关问题