Dozent Dozent - 4 months ago 11
Java Question

Sorting Set<String> based on index names in java

My need is to sort Set data, based on specific index names. I have following data:

txt_4: somevalue
txt_2: somevalue
txt_1: somevalue
txt_0: somevalue
txt_3: somevalue


How can I sort this data? Thanks.

UPDATE:

Expected data after sorting:

txt_0: somevalue
txt_1: somevalue
txt_2: somevalue
txt_3: somevalue
txt_4: somevalue

Answer

Use TreeSet object for that.

TreeSet elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

     Set<String> treeSet = new TreeSet<String>();
     treeSet.add("txt_4: somevalue");
     treeSet.add("txt_1: somevalue");
     treeSet.add("txt_0: somevalue");
     treeSet.add("txt_3: somevalue");
     System.out.println(treeSet);