我有多个树集,它们都有不同的值。我试图从每个树集中获取匹配元素并将其放入最终的树集中。
所以我正在寻找的是如果
树集一有一个 b c d
树集二有 b d e g
树集三有 b e d h
我的返回树集将有 b 和 d
我尝试过的代码是
TreeSet<String> uniqueWords = uniqueWords(words);
TreeSet[] results = new TreeSet[uniqueWords.size()];
int i = 0;
for (String word : uniqueWords) {
// get will return a TreeSet
results[i] = ((TreeSet)HashMap.get(word));
if (results[i] == null) {
return new TreeSet();
}
i++;
}
TreeSet finalList = new ReferenceSet();;
for (int step = 1; i < results.length; step++) {
finalList.retainAll(results[step]);
}
return finalList;`
最佳答案
您正在寻找的是多个集合的交集,可以通过 Collection#retainAll
来实现(正如您在问题中已经提到的那样)。如果你想要 final Set
要分开(而不是三个开头的 Set
之一),您可以使用以下内容:
SortedSet<String> intersection = new TreeSet<>(setA);
intersection.retainAll(setB);
intersection.retainAll(setC);
这是一个例子:
var setA = new TreeSet<>(List.of("a", "b", "c", "d"));
var setB = new TreeSet<>(List.of("b", "d", "e", "g"));
var setC = new TreeSet<>(List.of("b", "e", "d", "h"));
var intersection = new TreeSet<>(setA);
intersection.retainAll(setB);
intersection.retainAll(setC);
System.out.println(intersection);
输出:
[b, d]
关于java - 如何将多个树集中的匹配元素合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49885145/