Since the list is already sorted on amount, you just need to include the object Label in the list for the first time it appears. You can generate a new list with the exact elements if you use a dictionary to store the ids of the elements already entered. Like this:
public static List<Label> compact(List<Label> l)
{
Set<String> ids = new HashSet<>();
List<Label> toret = new ArrayList<>();
for(Label label: l) {
if ( !ids.contains( label.id ) ) {
ids.add( label.id );
toret.add( label );
}
}
return toret;
}
Antoher possibility, since we are using lists, would be to do the compaction "in place", i.e., using the same list. Take into account that this possibility uses less memory, but is slower (since it has to look for element 'i' for each time in loop, which can be expensive in a LinkedList).
public static void compactInPlace(List<Label> l)
{
Set<String> ids = new HashSet<>();
for(int i = 0; i < l.size(); ++i) {
if ( !ids.contains( l.get( i ).id ) ) {
ids.add( l.get( i ).id );
} else {
l.remove( i );
--i;
}
}
return;
}
Find the code here: http://ideone.com/B4Gggt
Hope this helps.