Posted In: Hashmap, Java Core

Hashmap/Hashtable uses in an enterprise application – example3

Use case – We have list of objects (in this case users). We want to remove duplicate users depending on some criteria. In this example with first name and last name. We do not have source of user class. So you cannot override equals and hashcode method.

package com.javausecase.hashmap3;

import java.io.Serializable;

public class User implements Serializable {
	private static final long serialVersionUID = 398805957846695098L;
	private String firstName;
	private String lastName;

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return "User [firstName="
		        + firstName + ", " + "lastName=" + lastName + "]";
	}

}
package com.javausecase.hashmap3;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class HashmapUsage3 {

	public static void main(String[] args) {
		HashmapUsage3 hashmapUsage3 = new HashmapUsage3();
		hashmapUsage3.removeDuplicateUsers();
	}

	private void removeDuplicateUsers() {
		ArrayList<User> userList = createTestData();
		Map<String, User> userMap = new HashMap<String, User>();
		for(User user : userList) {
			userMap.put(user.getFirstName()+user.getLastName(), user);
		}
		
		System.out.println(userMap);
	}

	private ArrayList<User> createTestData() {
		ArrayList<User> userList = new ArrayList<User>();
		User user1 = new User();
		user1.setFirstName("Bat");
		user1.setLastName("Man");
		User user2 = new User();
		user2.setFirstName("Super");
		user2.setLastName("Man");
		User user3 = new User();
		user3.setFirstName("X");
		user3.setLastName("Men");
		User user4 = new User();
		user4.setFirstName("Robin");

		user4.setLastName("Hood");
		User user5 = new User();
		user5.setFirstName("Bat");
		user5.setLastName("Man");
		userList.add(user1);
		userList.add(user2);
		userList.add(user3);
		userList.add(user4);
		userList.add(user5);
		return userList;
	}
}

Result
{SuperMan=User [firstName=Super, lastName=Man], XMen=User [firstName=X, lastName=Men], RobinHood=User [firstName=Robin, lastName=Hood], BatMan=User [firstName=Bat, lastName=Man]}

Tags: , ,

by , on January 30th, 2017

  • Categories