java - Compact a list based on a value -
having simple class such as:
public class label { public string id; public double amount; }
and having list following values (list sorted in amount
ascending order):
id amount ---------------- 1742 10 1742 11 1647 12 4217 13 1647 14 1742 15
is there simple way compact list lowest amount id
remains. so, after compaction, list should this:
id amount ---------------- 1742 10 1647 12 4217 13
here 1 way of doing it. method makeunique() keep labels have minimum amounts.
public class label { public string id; public double amount; public label(string id, double amount) { super(); this.id = id; this.amount = amount; } public static map<string, label> makeunique(list<label> list) { map<string, label> map = new hashmap<string, label>(); (label label : list) { if(!map.containskey(label.id)) map.put(label.id, label); } return map; } public static void main(string[] args) { list<label> list = new arraylist<label>(); list.add(new label("1742", 10)); list.add(new label("1742", 11)); list.add(new label("1647", 12)); list.add(new label("1647", 14)); map<string, label> map = makeunique(list); } }
Comments
Post a Comment