Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to sort elements of a set but unable to do so far. here is my code which i am trying to do

public static void main(String [] args){
    Set<String> set=new HashSet<String>();
    set.add("12");
    set.add("15");
    set.add("5");
    List<String> list=asSortedList(set);
}

public static
<T extends Comparable<? super T>> List<T> asSortedList(Collection<T> c) {
  List<T> list = new ArrayList<T>(c);
  Collections.sort(list);
  return list;
}

but this or other way is not working since its all time giving me the same order in which they have been filled 12,15,5

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
187 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use a SortedSet (TreeSet is the default one):

SortedSet<String> set=new TreeSet<String>();
set.add("12");
set.add("15");
set.add("5");
List<String> list=new ArrayList<String>(set);

No extra sorting code needed.

Oh, I see you want a different sort order. Supply a Comparator to the TreeSet:

new TreeSet<String>(Comparator.comparing(Integer::valueOf));

Now your TreeSet will sort Strings in numeric order (which implies that it will throw exceptions if you supply non-numeric strings)

Reference:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...