【问题标题】:Convert Map<Integer, List<Strings> to Map<String, List<Integer>将 Map<Integer, List<Strings> 转换为 Map<String, List<Integer>
【发布时间】:2022-09-30 21:08:12
【问题描述】:

我很难转换一个 Map ,它有一些整数作为键,随机字符串列表作为值。

e.g.
1 = [\"a\", \"b\", \"c\"]
2 = [\"a\", \"b\", \"z\"]
3 = [\"z\"]

到具有以该 int 作为键的整数的不同字符串的 Map

e.g.
a = [1, 2]
b = [1, 2]
c = [1]
z = [2,3]

这是我到目前为止得到的:

Map<Integer, List<String>> integerListMap; <- Initial list already populated
List<String> distinctStrings = new ArrayList<>();
SortedMap<String, List<Integer>> stringListSortedMap = new TreeMap<>();

for(Integer i: integers) {
    integerListMap.put(i, strings);
    distinctStrings.addAll(strings);
}
distinctStrings = distinctStrings.stream().distinct().collect(Collectors.toList());

for(String s : distinctStrings) {
    distinctStrings.put(s, )
}

提前致谢

  • 遍历您的源代码Map 并直接在该循环中填充结果。无需创建distinctStrings 列表。

标签: java dictionary


【解决方案1】:

遍历源映射的值并将每个值放入目标映射。

final Map<String, List<Integer>> target = new HashMap<>();
for (final Map.Entry<String, List<Integer>> entry = source.entrySet()) {
  for (final Integer i : entry.getValue()) {
    target.computeIfAbsent(i, k -> new ArrayList<>()).add(entry.getKey());
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    相关资源
    最近更新 更多