I need a Collection that sorts an element but does not remove duplicates.
I went for TreeSet .
Since TreeSet actually adds values ββto the fallback TreeMap :
public boolean add(E e) { return m.put(e, PRESENT)==null; }
And TreeMap removes duplicates using Comparators compare logic
I wrote a Comparator that returns 1 instead of 0 in case of equal elements. Therefore, in the case of equal elements, the TreeSet with this Comparator will not overwrite the duplicate and just sort it.
I tested it for simple String objects, but I need a set of custom objects.
public static void main(String[] args) { List<String> strList = Arrays.asList( new String[]{"d","b","c","z","s","b","d","a"} ); Set<String> strSet = new TreeSet<String>(new StringComparator()); strSet.addAll(strList); System.out.println(strSet); } class StringComparator implements Comparator<String> { @Override public int compare(String s1, String s2) { if(s1.compareTo(s2) == 0){ return 1; } else{ return s1.compareTo(s2); } } }
Is this approach perfect or is there a better way to achieve this?
EDIT
Actually, I have an ArrayList of the following class:
class Fund { String fundCode; BigDecimal fundValue; ..... public boolean equals(Object obj) {
I need all fundCode with highest fundValue
source share