我有一些属性文件保存在Map中。示例:
Map<String, String> map = new HashMap<>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Two");
map.put("4", "One"); 我想将Map<String, String>转换为
Map<String, List<String>> map = new HashMap<>(); 那应该是
<"One", ("1", "4")>
<"Two", ("2", "3")>我有一些代码,我想用Java 8风格重写。
private Map<File, List<File>> getAllFiles(Set<File> files) {
Map<File, File> inputFilesWithTskFile =
AppStorage.getInstance().getApplicationBean().getInputFilesWithTskFile();
List<File> tsks = new ArrayList<>();
for (Map.Entry<File, File> entry : inputFilesWithTskFile.entrySet()) {
if (files.contains(entry.getKey())) {
tsks.add(entry.getValue());
}
}
Map<File, List<File>> listTsk = new HashMap<>();
for (Map.Entry<File, File> entry : inputFilesWithTskFile.entrySet()) {
if (tsks.contains(entry.getValue())) {
List<File> files1 = listTsk.get(entry.getValue());
if (files1 == null) {
files1 = new ArrayList<>();
}
files1.add(entry.getKey());
listTsk.put(entry.getValue(), files1);
}
}
return listTsk;
}谢谢你的帮助。也许您知道一些教程,这些教程解释如何从Map创建Map,地图左侧应该有值,右侧应该是按值分组的键列表。
发布于 2018-04-06 14:50:17
如下所示:
private Map<File, List<File>> getAllFiles(List<File> files) {
return AppStorage.getInstance().getApplicationBean().getInputFilesWithTskFile()
.entrySet()
.stream()
.filter(e -> files.contains(e.getKey()))
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}也就是说,获取所有的filesWithTskFile,过滤出键不在files中的Map中的条目。然后将Map按value分组。
使用
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;一个更一般的例子,包括:
public static Map<String, List<String>> groupByValue(final Map<String, String> input) {
return input.entrySet().stream()
.collect(groupingBy(Entry::getValue, mapping(Entry::getKey, toList())));
}跑步:
final Map<String, String> 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->[3, 1]
B->[2, 4]扩大到:
public static Map<String, List<String>> groupByValue(final Map<String, String> input, final Set<String> 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->[1, 3]NB: --我使用的是Set,而不是List。Set保证其contains方法将在O(1)中运行,而对于List则在O(n)中运行。因此,List将是,非常低效的。根据输入的大小,在过滤之前将List复制到Set中可能会更好:
private Map<File, List<File>> getAllFiles(List<File> files) {
final Set<File> 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())));
}https://stackoverflow.com/questions/49695144
复制相似问题