2016-05-12 57 views
0

嗨我有两个数组列表列表l1和列表l2,名称,年龄,性别,uniqID,标记是列表中的数据。我想加入l1和l2而没有duplicates.uniqID对每个学生都是唯一的。我一直在循环所有的元素,并比较每一个元素。但是我的清单将有大约20k项目,因此循环花费了太多时间。我试过 all the answers from this post没有为我工作。有什么建议么。?合并模型元素ArrayList没有重复

+0

你覆盖'equals'在你的“人”类?删除像这篇文章http://stackoverflow.com/a/14361428/966852中建议的重复项应该在执行“equals”时工作。 – samjaf

+0

@Shanu:你可以使用'HashSet'或任何实现'set'接口的集合。 – AndiGeeky

回答

1

简单的例子:

public class Person{ 
    int id; 
    String name; 
    //fields, getter, setter, constructor omited.... 

    @Override 
    public boolean equals(Object o){ 
     if (!(o instanceof Person)){ 
      //implicit null check 
      return false; 
     } 
     return this.id==((Person)o).id; 
    } 

    @Override 
    public int hashCode(){ 
     return this.id; 
    } 
} 

Person确实现在实现equals和hashCode。 equals由java用来决定对象是否是另一个对象的重复。 hashCode本身不是必需的,但建议一起覆盖hashCodeequals

如果这两种方法来实现,你可以简单地使用在Java中积累的方法和数据结构:

随着名单:

List<Person> listA = new ArrayList<>(); 
List<Person> listB = new ArrayList<>(); 
// filling the lists omitted 
List<Person> mergedList=new ArrayList<>(); 
mergedList.addAll(listA); 
mergedList.removeAll(listB); 
mergedList.addAll(listB); 

或用套:

List<Person> listA = new ArrayList<>(); 
List<Person> listB = new ArrayList<>(); 
// filling the lists omitted 
Set<Person> mergedSet=new HashSet<>(); 
mergedSet.addAll(listA); 
mergedSet.addAll(listB); 
+0

我会马上试试。 – Sreyas

+0

尽管该列表正在消除所有重复项,但需要1分钟左右的时间。 – Sreyas

+0

您使用了哪个示例?使用'Set'的解决方案应该比使用'List'的解决方案执行得更好。如果合并后仍然需要列表的顺序,则可以使用“LinkedHashSet”。 – samjaf

0

你可以结合这两个arraylist并将其传递给HashSet对象 由于Set不包含可以执行的重复项

ArrayList<String> a=new ArrayList<String>(); 
ArrayList<String> b=new ArrayList<String>(); 

b.addAll(a); 

如果您想保留元素的顺序使用LinkedHashSet

LinkedHashSet<String> result=new LinkedHashSet<String>(b); 
+0

将这两个列表结合起来并将它们添加到'Set'中会比我们需要更多的工作。你可以调用'addAll'这两个列表到(空)Set。此外,问题是自定义类中没有“equals”和“hashCode”,这会阻止“Set”正常工作。 – samjaf