How to remove element from one list by comparing two lists

python compare two lists element wise
python check if two lists have same elements
python compare two lists of strings
subtract one list from another python
find common elements in two lists java
get uncommon elements from two lists java 8
how to remove list of objects from another list in java
how to compare two list objects in java

I have two Lists, say List1 and List2. I need to remove elements from List2 if that is already present in List1

To avoid ConCurrentModificationException, I have tried with ListIterator

employeeList1 // data present
employeeList2 // data present
ListIterator<Employee> zeroList=employeeList2.listIterator();

//remove employee if already present in list1
while(zeroList.hasNext()){
for(Employee employee : employeeList1){
                    if(zeroList.next().getID().equals(employee.getId())){
zeroList.remove();
                    }
                }
            }

I am getting the below exception inside the if condition

java.util.NoSuchElementException

It is possible that element might not be present in List1, but checking the condition is necessary.

You can use removeAll method on collection from which you want to remove the elements and pass the collection as arguments which contains the elements you want to remove.

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("p");
list2.add("q");
list2.removeAll(list1);
System.out.println(list2);

Removes a from list2 as it was present in list1 and prints p and q only,

[p, q]

Edit: Here is a sample code for Employee class while yours might be a different one but as you said your key is employeeId hence equals and hashCode methods needs to play on employeeId only.

static class Employee {
    private long employeeId;
    private String name;
    // whatever more variables

    public Employee(long employeeId, String name) {
        this.employeeId = employeeId;
        this.name = name;
    }

    public String toString() {
        return String.format("Employee[employeeId=%s, name=%s]", employeeId, name);
    }

    @Override
    public boolean equals(Object o) {
        if (o instanceof Employee) {
            return this.employeeId == ((Employee) o).employeeId;
        }
        return false;
    }

    @Override
    public int hashCode() {
        return new Long(employeeId).hashCode();
    }
}

public static void main(String[] args) throws Exception {
    List<Employee> list1 = new ArrayList<>();
    list1.add(new Employee(1, "a"));
    list1.add(new Employee(2, "b"));
    list1.add(new Employee(3, "c"));
    List<Employee> list2 = new ArrayList<>();
    list2.add(new Employee(1, "a"));
    list2.add(new Employee(4, "d"));
    list2.add(new Employee(5, "e"));
    list2.removeAll(list1);
    System.out.println(list2);
}

Try using this code and see what it prints and then just comment both equals and hashCode method and then see what happens. After you comment those two methods, the object present in list1 will not be removed as list doesn't know when the two objects are equal.

How to Compare Two Lists in Python, List comprehension to compare two set a pointer element 'x' to the list l1� // Remove all by matching on the object (this works as the two lists contain the same objects as opposed // to different object instances containing the same data - be careful with this) myPeople.RemoveAll(x => myListOfPeopleToRemove.Contains(x));

What is wrong with the simpler

List<Employee> employeeList1
List<Employee> employeeList2

for (Employee employee : employeeList2) {
   if (employeeList1.contains(employee)) {
      employeeList2.remove(employee)
   }
}

Of course you would have to synchronize the List calls if using multiple threads.

Python List, Python List: Insert, modify, remove, slice, sort, search element(s) and largest and the smallest items in a list; Compare two lists in Python? Mention Element to Remove List Element Using remove () The remove () function uses the list element as the argument to delete. You have to pass only the single element which you want to delete. The function requires only one element and can delete the only single element from the list.

You could use the Apache commons-collections

library:

List<String> newList = ListUtils.union(list1, list2);

Difference Between Two Lists using Python Set & Without Set, Other non-set methods compare two lists element by element and collect the unique we'll be appending every non-matching item to a new (and empty) list. Example 1: Make a function for both lists. If there are common elements in both the list, then it will return common elements in list c. If both lists do not contain any common elements then it will return an empty list. a=[2,3,4,5] b=[3,5,7,9] def common(a,b): c = [value for value in a if value in b] return c d=common(a,b) print(d) Both the list have common elements 3 & 5, So it will return [3,5]. [3, 5] Using set() function. Example 2: Using set( ) function, We can return common elements

MULTIPLE LIST COMPARATOR, A free online tool to find data intersection and draw Venn diagrams. It accepts data as item lists or as a table with the input data in columns. It displays graphical � Python Difference Between Two Lists. Lists in Python can be performed in different ways, but it depends on the outcome required. Two popular methods of comparison are set() and cmp(). The set() function creates an object that is a set object. The cmp() function is used to compare two elements or lists and return a value based on the arguments

11. Lists — How to Think Like a Computer Scientist: Learning with , We have already seen that we can assign list values to variables or pass lists as We can also remove elements from a list by assigning an empty list to them: We can test whether two names refer to the same object using the is operator:. It returns a Collector which collects all the input elements into a List, in an encounter (unordered) order. Example. In the following example, we have created two ArrayList firstList and secondList of String type. The filter() method returns a List of common elements which are present in both Lists.

Intersection of Two Lists in Java, Learn how to retrieve the intersection of two Lists. First, we remove the duplicated elements with distinct. Then, we use the filter How does the contains method decide whether a specific object appears in a list? Based on� If two arraylists are not equal and we want to find what are additional elements in first list in comparison to second list then we can use this method. It uses removeAll () method which removes all elements of second list from first list. It leaves only additonal elements in first list. Find additional elements in a list

Comments
  • My Employee entity contains several variables. So removing via object might not work always. I need to remove based on employeeId
  • You can still use the same method even if your list stores custom object. Just make sure you implement equals() and hashCode() method in your class whose object is stored in your list. And as you are saying based on employeeId, just implement your both methods equals and hashCode methods based on employeeId Can you add the code of your custom class in your post? I'll get you specific pointers then.
  • Is it necessary to override hashcode since I am using arraylist here
  • small confusion here... I need to remove "a" only from list 2 , not from list 1. Means data present in List 1 should be removed from list2
  • Sorry for the little confusion. Overriding only equals() method should be enough because you aren't using any HashMap or HashSet which indeed uses hashCode() method. But in general, it is a good practice always to implement both equals as well as hashCode so that if the object is used somewhere as key in a hashing data structure, it behaves consistent and well.
  • My Employee entity contains several variables. So removing via object might not work always. I need to remove based on employeeId
  • And if you implement Employee.equals() in a way that employee1.equals(employee2) if employeeIds are equal? Or do you need another equality elsewhere?