Remove Duplicate Objects in ArrayList

kiri :

All,

I have a object

public class Device {

     public String getUserId() {
        return userId;
    }
    public String getDeviceId() {
        return deviceId;
    }

}

I get all the List of Values

     List<Device> uList = getList();

In the List i have a duplicate values Based on userId Now i want to get Unique list which will remove the duplicates of userId

How can i acheive it, I am very much new to Java

shmosel :

The simplest way is to create a Map where the key is the userId:

Map<String, Device> map = new HashMap<>();
devices.forEach(d -> map.put(d.getUserId(), d));
List<Device> uniques = new ArrayList<>(map.values());

Or, using streams:

Map<String, Device> map = devices.stream()
        .collect(Collectors.toMap(Device::getUserId, d -> d, (a, b) -> a));
List<Device> uniques = new ArrayList<>(map.values());

Alternatively, you can dump them in a TreeSet with a comparator that checks userId:

Set<Device> set = new TreeSet<>(Comparator.comparing(Device::getUserId));
set.addAll(devices);
List<Device> uniques = new ArrayList<>(set);

All of this assumes you're not concerned about discrepancies in deviceId. Otherwise, take a look at Map.merge() or the corresponding Collectors.toMap() overload.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=309282&siteId=1