The method of removing duplicate object by Java Set

  • 2020-05-30 20:16:11
  • OfStack

Examples are as follows:


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 *  Author: CP
 * <br /> Class description: set Set against String  The type and 8 Big base data types   Filter out duplicate data , If you are storing other types of objects, you need to override them hashCode Methods and equals methods , when equals  When you compare equals, you compare hashCode value  hashCode The value of the   if 1 To words , They don't put it in set
 */
public class SetDemo {
	
	public static void main(String[] args) {
		Set<String> nameSet = new HashSet<String>();
		nameSet.add(" zhang 3");
		nameSet.add(" li 4");
		nameSet.add(" The king 5");
		nameSet.add(" zhang 3");
		
		//  The output   zhang 3	 li 4	 The king 5
		for(String name : nameSet){
			System.out.print(name + "\t");
		}
		// List Collections remove duplicate base data 
		List<String> nameList = new ArrayList<String>();
		nameList.add(" zhang 3");
		nameList.add(" li 4");
		nameList.add(" The king 5");
		nameList.add(" zhao 6");
		nameSet.addAll(nameList);
		
		//  The output   zhang 3	 li 4	 The king 5	 zhao 6
		for(String name : nameSet){
			System.out.print(name + "\t");
		}
		
		//  Remove the number and username 1 The sample of   Object that needs to be overridden  equals  methods   and  hashCode methods 
		User admin = new User(1, "admin");
		User user = new User(2, "user");
		User user1 = new User(2, "user");
		User admin1 = new User(3, "admin");
		
		
		Set<User> userSet = new HashSet<User>();
		userSet.add(admin);
		userSet.add(user);
		userSet.add(admin1);
		userSet.add(user1);
		//  Input the results  admin1	admin3	user2
		for(User u : userSet){
			System.out.print(u.username + u.id + "\t");
		}
		
		System.out.println(user.equals(null));
	}
}

class User{
	
	protected Integer id;
	
	protected String username;
	
	public User(Integer id, String username){
		this.id = id;
		this.username = username;
	}


	/**
	 *  If the object type is User  if   It returns true  To compare hashCode value 
	 */
	@Override
	public boolean equals(Object obj) {
		if(obj == null) return false;
		if(this == obj) return true;
		if(obj instanceof User){ 
			User user =(User)obj;
//			if(user.id = this.id) return true; //  Only compare id
			//  To compare id and username 1 Return on time true  And then we'll compare  hashCode
			if(user.id == this.id && user.username.equals(this.username)) return true;
			}
		return false;
	}



	/**
	 *  rewrite hashcode  Method, return hashCode  Don't 1 The sample is identified as a different object 
	 */
	@Override
	public int hashCode() {
//		return id.hashCode(); //  Only compare id . id1 Samples are not added to the collection 
		return id.hashCode() * username.hashCode();
	}

	
}

Related articles: