我正在寻求有关是否有比我在下面的代码中所执行的方法更有效的方法的反馈。
基本上,给出此地图:
Set<String> A_Set = new HashSet<>(Arrays.asList("1111", "2222", "5555"));
Set<String> B_Set = new HashSet<>(Arrays.asList("3333", "4444"));
Set<String> C_Set = new HashSet<>(Arrays.asList("6666"));
Set<String> D_Set = new HashSet<>(Arrays.asList("2222", "5555", "6666"));
Map<String, Set<String>> values = new HashMap<>();
values.put("A", A_Set);
values.put("B", B_Set);
values.put("C", C_Set);
values.put("D", D_Set);
如下所示:
如何创建Map<String, List<Boolean> map
使其看起来像这样:
以最有效的方式。我的实数Map
每个Set
有数千个值,但只有4个Sets
(A,B,C,D)。
这是我当前的代码。您能想到一种更有效的方法吗?
import java.util.*;
public class MapToMap {
public static void main(String[] args) {
Set<String> A_Set = new HashSet<>(Arrays.asList("1111", "2222", "5555"));
Set<String> B_Set = new HashSet<>(Arrays.asList("3333", "4444"));
Set<String> C_Set = new HashSet<>(Arrays.asList("6666"));
Set<String> D_Set = new HashSet<>(Arrays.asList("2222", "5555", "6666"));
Map<String, Set<String>> values = new HashMap<>();
values.put("A", A_Set);
values.put("B", B_Set);
values.put("C", C_Set);
values.put("D", D_Set);
Map<String, List<Boolean>> exists = new HashMap<>();
for (Map.Entry<String, Set<String>> v : values.entrySet()) {
for (String val : v.getValue()) {
if (exists.containsKey(val)) {
List<Boolean> list = exists.get(val);
list = addValue(v.getKey(), list);
exists.put(val, list);
} else {
List<Boolean> newList = new ArrayList<>(Arrays.asList(false, false, false, false));
newList = addValue(v.getKey(), newList);
exists.put(val, newList);
}
}
}
for (Map.Entry<String, List<Boolean>> s : exists.entrySet()) {
System.out.println(s);
}
}
private static List<Boolean> addValue(String key, List<Boolean> listToUse) {
List<Boolean> newList = new ArrayList<>();
if (Objects.equals("A", key)) {
newList.addAll(Arrays.asList(true, listToUse.get(1), listToUse.get(2), listToUse.get(3)));
} else if (Objects.equals("B", key)) {
newList.addAll(Arrays.asList(listToUse.get(0), true, listToUse.get(2), listToUse.get(3)));
} else if (Objects.equals("C", key)) {
newList.addAll(Arrays.asList(listToUse.get(0), listToUse.get(1), true, listToUse.get(3)));
} else if (Objects.equals("D", key)) {
newList.addAll(Arrays.asList(listToUse.get(0), listToUse.get(1), listToUse.get(2), true));
}
return newList;
}
}
答案 0 :(得分:1)
这是使用流的解决方案:
Map<String, List<Boolean>> exists = values.values()
.stream()
.flatMap(Set::stream)
.distinct()
.collect(Collectors.toMap(v -> v, v -> Stream.of("A", "B", "C", "D")
.map(k -> values.get(k).contains(v))
.collect(Collectors.toList())));