[英]Joining array lists of set in Java
我有兩個集合列表。 我想加入他們如下。 對兩個列表進行排序然后加入列表的每個索引的集合是一種有效的方法嗎?
List A
=======
{a, 2, 3}
{b, 17, 6}
{c, -1, 5}
List B
=======
{b, "Tommy", "Hill"}
{a, "W", "-1"}
{c, "l", "O"}
Output
======
{a, 2, 3, "W", "-1"}
{b, 17, 6, "Tommy", "Hill"}
{c, -1, 5, "l", "O"}
您應該使用set.retainAll()
來查找兩個集合的交集。 如果存在交集,則可以使用 JAVA 8 流功能來連接兩組:
Set<String> combinedSet = Stream.concat(Set1.stream(), set2.stream())
.collect(Collectors.toSet());
創建列表
List <String> A1=Arrays.asList(new String[] {"a","2","3"});
List <String> A2= // complete it
List <String> A3= // complete it
List <String> B1=Arrays.asList(new String[] {"b","Tommy","Hill"});
List <String> B2= // complete it
List <String> B3= // complete it
將它們插入 Set<List>
Set<List<String>> A=new HashSet<List<String>>(); A.add(A1); A.add(A2); A.add(A3);
Set<List<String>> B=new HashSet<List<String>>(); B.add(B1); B.add(B2); B.add(B3);
迭代你的集合
for (List <String> Ax: A)
{
String the_index=Ax.get(0);
for (List <String> Bx: B)
搜索第一項
if (the_index.equals(Bx.get(0)))
// Join
{
List <String> result=new ArrayList<String>();
獲取第一個列表
result.addAll(Ax);
在第二個列表中添加延續
result.addAll(Bx.subList(1, Bx.size()));
System.out.println(result);
}
希望能幫助到你 !
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.