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

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

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

  1. // Create a map
  2. Map<String, Set<String>> map = new HashMap<String, Set<String>>();
  3. // Create setA
  4. Set<String> setA = new HashSet<String>();
  5. setA.add("A");
  6. setA.add("B");
  7. // There could be more (or less) values in setA
  8. // Create setB
  9. Set<String> setB = new HashSet<String>();
  10. setB.add("X");
  11. setB.add("Y");
  12. // There could be more (or less) values in setB
  13. // Create setC
  14. Set<String> setC = new HashSet<String>();
  15. setC.add("1");
  16. setC.add("2");
  17. // There could be more (or less) values in setC
  18. // Add sets to map
  19. map.put("a", setA);
  20. map.put("b", setB);
  21. map.put("c", setC);
  22. // There could be more sets to add to the map
  1. /*
  2. * Combine each value from each set in the
  3. * map {a=[A, B], b=[X, Y], c=[1, 2]} to
  4. * unique strings. Output should be:
  5. * A X 1
  6. * A X 2
  7. * A Y 1
  8. * A Y 2
  9. * B X 1
  10. * B X 2
  11. * B Y 1
  12. * B Y 2
  13. * ... more combinations if there are more values
  14. */
gdx19jrr

gdx19jrr1#

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

agyaoht7

agyaoht72#

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

  1. Set<Set<String>> sets = new LinkedHashSet<>(List.of(
  2. new LinkedHashSet<>(List.of("A", "B")),
  3. new LinkedHashSet<>(List.of("X", "Y")),
  4. new LinkedHashSet<>(List.of("1", "2"))));
  1. Set<String> set = sets.stream()
  2. .reduce((s1, s2) -> s1.stream().flatMap(e1 ->
  3. s2.stream().map(e2 -> e1 + ":" + e2))
  4. .collect(Collectors.toCollection(LinkedHashSet::new)))
  5. .orElse(Set.of(""));
  1. set.forEach(System.out::println);
  2. // A:X:1
  3. // A:X:2
  4. // A:Y:1
  5. // A:Y:2
  6. // B:X:1
  7. // B:X:2
  8. // B:Y:1
  9. // B:Y:2
展开查看全部

相关问题