E2r*_*abi 0 java algorithm collections for-loop hashmap
我在一个hashmap里面有两个Set,我希望在另一个Set中合并那些值:
for (Map.Entry<String, HashSet<String>> entry : myhashmap.entrySet()) {
// in the first iteration entry.getValue() give me elementValues1 Set
// and the second give elementValues2
}
Run Code Online (Sandbox Code Playgroud)
例如,我在第一次迭代中的第一个HashSet包含这些值:A, B.
喜欢 :
Set<String> elementValues1 = new HashSet<String>();
elementValues1.add("A");
elementValues1.add("B");
Run Code Online (Sandbox Code Playgroud)
我在第二次迭代中的第二个Set包含:C, D.
喜欢 :
Set<String> elementValues2 = new HashSet<String>();
elementValues2.add("C");
elementValues2.add("D");
Run Code Online (Sandbox Code Playgroud)
我想在循环中创建另一个组合两个Set的值:Like:
Set<String> elementValues3 = new HashSet<String>();
Run Code Online (Sandbox Code Playgroud)
elementValues3 应包含:AC AD BC BD
有人可以帮我解决这个问题,提前谢谢
如果你真的想要String对象-分隔符,只需循环两个集合并将合并的值添加到第三个:
Set<String> elementValues3 = new HashSet<String>();
for (String s1: elementValues1) {
for (String s2: elementValues2) {
elementValues3.add(s1 + "-" + s2);
}
}
Run Code Online (Sandbox Code Playgroud)
得到的结果将是:
[AC,AD,BC,BD]
在Java 8中,您可以从流中受益:
Set<String> newSet
= elementValues1.stream()
.flatMap(a -> elementValues2.stream()
.map(b -> a + '-' + b))
.collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |