sách gpt4 ai đã đi

java - 使用 Java 8 流将 Map 转换为 Map>

In lại 作者:塔克拉玛干 更新时间:2023-11-01 22:05:48 29 4
mua khóa gpt4 Nike

我有一些保存在 map 中的属性文件。示例:

Map map = new HashMap<>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Two");
map.put("4", "One");

我想转换 Mapđến

Map> map = new HashMap<>(); 

应该是

<"One", ("1", "4")>
<"Two", ("2", "3")>

我有一些代码想用 Java 8 风格重写。

  private Map> getAllFiles(Set files) {
Map inputFilesWithTskFile =
AppStorage.getInstance().getApplicationBean().getInputFilesWithTskFile();

List tsks = new ArrayList<>();
for (Map.Entry entry : inputFilesWithTskFile.entrySet()) {
if (files.contains(entry.getKey())) {
tsks.add(entry.getValue());
}
}
Map> listTsk = new HashMap<>();
for (Map.Entry entry : inputFilesWithTskFile.entrySet()) {
if (tsks.contains(entry.getValue())) {
List files1 = listTsk.get(entry.getValue());
if (files1 == null) {
files1 = new ArrayList<>();
}
files1.add(entry.getKey());
listTsk.put(entry.getValue(), files1);
}
}
return listTsk;
}

感谢您的帮助。也许你知道一些解释如何从左侧应该有值的 Map 创建 Map 的教程,右侧应该是按值分组的键列表。

1 Câu trả lời

类似下面的内容:

private Map> getAllFiles(List files) {
return AppStorage.getInstance().getApplicationBean().getInputFilesWithTskFile()
.entrySet()
.stream()
.filter(e -> files.contains(e.getKey()))
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}

即获取所有filesWithTskFile,过滤掉Bản đồ中key不在files中的条目。然后按 giá trị Phải Bản đồ 进行分组。


sử dụng

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;

一个更通用的示例,包括:

public static Map> groupByValue(final Map input) {
return input.entrySet().stream()
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}

chạy:

final Map example = Map.of(
"1", "A",
"2", "B",
"3", "A",
"4", "B"
);

groupByValue(example).forEach((k, v) -> System.out.printf("%s->%s%n", k, v));

đưa cho:

A->[3, 1]
B->[2, 4]

扩展到:

public static Map> groupByValue(final Map input, final Set take) {
return input.entrySet().stream()
.filter(e -> take.contains(e.getKey()))
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}

并运行:

groupByValue(example, Set.of("1", "3")).forEach((k, v) -> System.out.printf("%s->%s%n", k, v));

đưa cho:

A->[1, 3]

Để ý:我使用Bộ Còn hơn làDanh sách 作为过滤器。 Bộ 保证其 contains 方法将在 O(1) 中运行,而 Danh sách 将在 O(1) 中运行O(n)。所以 Danh sách Sẽ非常效率低下。根据输入的大小,您实际上最好将 Danh sách 复制到 Bộ before 过滤中:

private Map> getAllFiles(List files) {
final Set filter = Set.copyOf(files);
return AppStorage.getInstance().getApplicationBean().getInputFilesWithTskFile()
.entrySet()
.stream()
.filter(e -> filter.contains(e.getKey()))
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}

关于java - 使用 Java 8 流将 Map 转换为 Map>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695144/

29 4 0
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com