If there are two sets, how to get their intersection and union quickly in java?
1. Give two List sets first
List<String> listA = new ArrayList<String>();
List<String> listB = new ArrayList<String>();
listA.add("A");
listA.add("B");
listB.add("B");
listB.add("C");
2. intersection
listA.retainAll(listB); System.out.println(listA); Print results: [B]
3. join and union
// If we don't do the first step, we will take the union with repeated elements
listA.removeAll(listB);
listA.addAll(listB);
System.out.println(listA);
//Print results:
[A, B, C]
4. difference sets
listA.removeAll(listB); System.out.println(listA); Print results: [A]
5. The data in the list is an object, not a basic data type
The basic data type of java is used above. If it is not a basic data type, we can override the methods in the class as follows:
(1) First, create a class as a generic type in the List:
User.java
package com.list;
public class User {
private String id;
private String name;
public User(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
User u = (User) obj;
return id.equals(u.getId()) && name.equals(u.getName());
}
@Override
public int hashCode() {
return id.hashCode();
}
}
(2) Take no duplicate union operation:
public class RemoveRepetition {
public static void main(String[] args) {
List<User> listA = new ArrayList<User>();
List<User> listB = new ArrayList<User>();
User user1 = new User("1", "a");
User user2 = new User("2", "b");
User user3 = new User("3", "c");
listA.add(user1);
listA.add(user2);
listB.add(user2);
listB.add(user3);
listA.removeAll(listB);
listA.addAll(listB);
for(User u : listA) {
System.out.println(u.getId() + ":" + u.getName());
}
}
}
//Print results:
1:a
2:b
3:c
(3) Fetch intersection operation
public class RemoveRepetition {
public static void main(String[] args) {
List<User> listA = new ArrayList<User>();
List<User> listB = new ArrayList<User>();
User user1 = new User("1", "a");
User user2 = new User("2", "b");
User user3 = new User("3", "c");
listA.add(user1);
listA.add(user2);
listB.add(user2);
listB.add(user3);
listA.retainAll(listB);
for(User u : listA) {
System.out.println(u.getId() + ":" + u.getName());
}
}
}
//Print results:
2:b