0

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.

Andreo Vieira
  • 360
  • 2
  • 8
  • what is the role of the `Element` class ? – Salah Eddine Taouririt Apr 17 '13 at 21:43
  • The `Element` holds information about a chemical element found in a sample area. One sample have multiple areas, and an area have multiples elements. In one given area, an element is unique.. The `value` field is a float value that I'll use later for similarity comparisons. Basically what I need is to transform an `ArrayList` in an `ArrayList` where each entry is the element with bigger value in all sample/areas. – Andreo Vieira Apr 17 '13 at 21:46
  • how do you represent the string (for example "ELEMENT C") in the `ensemble` class ? a private field holding the name of the chemical element ? – Salah Eddine Taouririt Apr 17 '13 at 21:57
  • The class `Element` has some fields, one of them is the element name. – Andreo Vieira Apr 17 '13 at 22:29

1 Answers1

0

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);
}
Zim-Zam O'Pootertoot
  • 17,888
  • 4
  • 41
  • 69