![](/img/trans.png)
[英]How to populate a hashmap with the keys in one set and the values in another set
[英]Combine keys and values of a HashMap to a Set
我有一個HashMap<Integer, Integer>
,唯一鍵可以有重復的值。 有沒有辦法將HashMap轉換為Set<Integer>
,其中包含鍵和值的唯一整數。
通過迭代keySet()和.values(),這絕對可以在兩個循環中完成。 我想知道這是否可以在java 8流中使用。
您可以使用stream函數組合值和鍵:
Map<Integer, Integer> map = ...
Set<Integer> total = Stream.concat(
map.keySet().stream(),
map.values().stream()
).collect(Collectors.toSet());
這使用map的keySet().stream()
和values().stream()
來獲取兩者的流,然后使用Stream.concat
連接它們,最后將它變成一個集合。 對.toSet()
的調用可以防止重復元素,因為一個集合不能包含重復元素。
如果鍵是double,並且值是浮點數,也可以使用此技巧,在這種情況下,java將返回最大的公共分隔符類,在這種情況下是Number。
兩次調用addAll()
很簡單,因為地獄而且非常易讀,所以這應該是你的解決方案。 但是,如果您希望滿足您的好奇心,您可以使用此基於流的解決方案(可讀性較差,可能效率較低):
Map<Integer, Integer> map = ...;
Set<Integer> result = map.entrySet()
.stream()
.flatMap(e -> Stream.of(e.getKey(), e.getValue()))
.collect(Collectors.toSet());
您可以將所有鍵作為一組獲取,然后使用addAll
添加所有值
Map<Integer, Integer> map = ...
Set<Integer> set = new HashSet<>(map.keySet());
set.addAll(map.values());
如果你真的想要使用Java 8流,你可以做以下但我不知道這會更好:
Map<Integer, Integer> map = ...
Set<Integer> set = new HashSet<>();
map.keySet().stream().forEach(n -> set.add(n));
map.values().stream().forEach(n -> set.add(n));
或者看看所有其他解決方案,但在我看來,一個簡單的addAll
在這里效果最好。 它應該是最有效和最可讀的方式。
您可以在條目集上迭代一次,這將為您提供所有對。 無論你是否通過流API執行它都無關緊要,因為此操作的復雜性保持不變。
public class StreamMapTest {
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
map.put(1, 20);
map.put(2, 20);
map.put(3, 10);
map.put(4, 30);
map.put(5, 20);
map.put(6, 10);
Set<Integer> result = map.entrySet().stream()
.flatMap(e -> Stream.of(e.getKey(), e.getValue()))
.collect(Collectors.toSet());
System.out.println(result);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.