Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
488 views
in Technique[技术] by (71.8m points)

判断List<Set<String>>中set是否有交集 有的话就取并集 返回合并后的List<Set> 集合

java多个集合之间如果有交集就合并, 然后返回合并后的list

现在有List<Set<String>> list 集合

Set<Integer> set1 = new HashSet<Integer>() {{
    add(1);
    add(3);
    add(4);
}};

Set<Integer> set2 = new HashSet<Integer>() {{
    add(1);
    add(2);
    add(3);
}};

...
set3
set4

list.add(set1);
list.add(set2);
list.add(set3);
list.add(set4);
...

现在的需求是 判断list中的set是不是相互有交集, 只要有一个相同元素的set 就合并取并集放到newSet1 中 最后期望返回的是合并后的List<newSet>

请大佬指教, 有什么好的算法可以实现


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

直接求重复算了,简单明了

@Test
public void setTest(){
    Set<Integer> one = Sets.newHashSet(1,2,3);
 Set<Integer> two = Sets.newHashSet(1,4,3);
 List<Set<Integer>> list = Lists.newArrayList(one,two);
 Set<Integer> three = list.stream().flatMap(Collection::stream).filter(predicate()).collect(Collectors.toSet());
 System.out.println(three);
}
private Predicate<Integer> predicate(){
    Set<Integer> set = Sets.newHashSet();
 return i->!set.add(i);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...