Java ArrayList merge without duplicates based on a value -
i have class called sample
, class has property arraylist<area>
, , area
contains 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 getmergeddata()
sample
class merges every arraylist<elements>
each of it's area, keeping element 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, method must return this: ("element k" => 10.1, "element c" => 5.5, "element as" => 15.0, "element o" => 5.8"
i can't figure out how can in fashion way.
if lists' elements same order, e.g. k
element first, c
element second, etc., element-by-element comparison. otherwise, can sort them on element names , element-by-element comparison (this nlog(n) if use sort algorithm), or else put in hashmap element name key , value value.
hashmap map = new hashmap(); for(int = 0; < list1.size(); i++) { element e = list1.get(i); map.put(e.name, e.value); } for(int = 0; < list2.size(); i++) { element e = list2.get(i); if(map.get(e.name) < e.value) map.put(e.name, e.value); }
Comments
Post a Comment