在Java中加入set的数组列表

时间:2015-12-23 10:04:31

标签: 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"}  

2 个答案:

答案 0 :(得分:0)

您应该使用set.retainAll()查找两组的交集。如果存在交集,则可以使用JAVA 8流特征来连接两个集合:

Set<String> combinedSet = Stream.concat(Set1.stream(), set2.stream())
                .collect(Collectors.toSet());

答案 1 :(得分:0)

创建列表

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&lt;列表&gt;

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);
                }

希望它有所帮助!