javaarraylistmergeno-duplicates

Java ArrayList merge without duplicates based on a value


I have a class called Sample, this class has a property that is an ArrayList<Area>, and an Area contains an ArrayList<Elements>

public class Sample {
    private ArrayList<Area> sampleAreas;
    public ArrayList<Element> getMergedData()
    {
        ...
    }
    ...
}

public class Area {
    private ArrayList<Element> areaElements
    ...
}

public class Element {
    private String name;
    private Float value;
    ...
}

I need that the getMergedData() from Sample class merges every ArrayList<Elements> from each of it's area, keeping the element with bigger value.

Ex:

Area 1: ("Element K" => 1.0, "Element C" => 0.5, "Element AS" => 15.0)

Area 2: ("Element K" => 10.1, "Element C" => 5.5, "Element AS" => 2.9, "Element O" => 1.5)

Area 3: ("Element C" => 2.8, "Element AS" => 0.5, "Element O" => 5.8)

Area 4: ("Element K" => 3.25, "Element AS" => 2.5, "Element O" => 0.1)

So, that method must return something like this: ("Element K" => 10.1, "Element C" => 5.5, "Element AS" => 15.0, "Element O" => 5.8"

I can't figure out how can I do this in a fashion way.


Solution

  • If the lists' elements are the same order, e.g. their K element is first, their C element is second, etc., then just do an element-by-element comparison. Otherwise, you can sort them on their element names and then do an element-by-element comparison (this is nlog(n) if you use a good sort algorithm), or else put everything in a HashMap with the element name as key and value as value.

    HashMap map = new HashMap();
    for(int i = 0; i < list1.size(); i++) {
        Element e = list1.get(i);
        map.put(e.name, e.value);
    }
    for(int i = 0; i < list2.size(); i++) {
        Element e = list2.get(i);
        if(map.get(e.name) < e.value)
            map.put(e.name, e.value);
    }