【问题标题】:Combine multiple sets in a map to unique strings将地图中的多个集合组合成唯一的字符串
【发布时间】:2020-12-01 14:14:41
【问题描述】:

我需要将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
 */

【问题讨论】:

    标签: java dictionary set


    【解决方案1】:

    您可以为此使用方法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
    

    【讨论】:

      【解决方案2】:

      最后我最终使用了Guava library for creating the cartesian product。使用方便,性能好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 2011-06-21
        • 2019-03-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多