列表数组检测非唯一值

时间:2016-08-09 13:59:01

标签: java android

addAll有效但removeAll在两个数组列表中都有相似的值

  List<Student> sourceList = new ArrayList<Student>(students);
    List<Student> destinationList = new ArrayList<Student>(students1);

    sourceList.removeAll(students1);
    destinationList.removeAll(students);
    sourceList.addAll(destinationList);

    for (Student student : sourceList) {
        System.out.println("SIM:::Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
    }

2 个答案:

答案 0 :(得分:0)

您可以改为使用Hash Set,但不允许使用重复项。

import java.util.*;

public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      HashSet<String> hs = new HashSet<String>();

      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("C");

      // trying to add duplicate elements to the hash set
      hs.add("C");
      hs.add("B");
      hs.add("A");

      // Only stores one of each, and orders them.
      System.out.println(hs); // [A, B, C]
   }
}

答案 1 :(得分:0)

最终我得到了解决方案。 它在两个listArray中显示类似的项目。

 private void findsimalarity() {

    List<Student> sourceList = new ArrayList<>();
    List<Student> destinationList = new ArrayList<>();

    sourceList.addAll(students);
    destinationList.addAll(students1);

    destinationList.removeAll(sourceList);

    sourceList.removeAll(destinationList);

    if (sourceList.size() >= destinationList.size()) {
        //destination list contains similar items
        for (Student student : destinationList) {
            System.out.println("SIMILAR:::Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
        }
    } else {
        //source list contains similar items
        for (Student student : sourceList) {
            System.out.println("SIMILAR:::Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
        }
    }

}