How to sort and eliminate the duplicates from ArrayList?

  • A+

I have a ArrayList of String type which contains values as range = {300-400, 100-200, 500-600, 300-400, 500-600}

I need to sort it out and remove the duplicates present in it.

The final output should be range = {100-200,300-400,500-600}.

Can anyone help me ?


Use a TreeSet:

Set<String> sortedAndDistinct = new TreeSet<>(list); 

A Set allows by definition only distinct values. And a TreeSet sorts the values according to their natural ordering (if no Comparator is provided at creation).

For Strings the natural ordering is lexicographically, in other words, a is smaller than z or in your case 100-200 is smaller than 500-600


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: