2

Im using hashmap and arraylist... How to sort the arraylist ? eg) In hashmap values are in order like one,two,three,four,five but i stored these values in arraylist the order changed like three,one,five,two,four

In my code groupList,gnamelist and newList are all arraylist... In print sts PLACES are in correct order but while print on NEWLIST PLACES the order changed How to sort this in order?

My code

    HashMap<String, String> map = new HashMap<String, String>();
      // adding each child node to HashMap key => value
      map.put(TAG_PLACE, gname);
      map.put(TAG_HOTEL,lname);
     // adding HashList to ArrayList
      groupList.add(map);
      gnamelist.add(gname);
      System.out.println("PLACES" + gnamelist);
      List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(gnamelist));
      Collections.sort(newList,Collections.reverseOrder());
      System.out.println("NEWLIST PLACES" + newList);

2 Answers 2

1

HashSet will store elements in an unordered fashion, and is likely the culprit of your element reordering.

List<String> newList = new ArrayList<String>(new HashSet<String>(gnamelist));

Also consider using LinkedHashMap/LinkedHashSet, which preserves the ordering of elements added to it.

Alternatively try the following:

gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>();
newList.addAll(gnamelist);
Sign up to request clarification or add additional context in comments.

2 Comments

Why are you using the HashSet at all? You can just use AddAll to add all elements from one list to another. (See my revised answer above)
ok then how to sort the 'grouplist' array in that i have add map values, two values..
1

Try

Collections.sort(newList);

Edit:

If you want to sort in reverse use this

Collections.sort(newList,Collections.reverseOrder());

Important:

if you want to preserve insertion order, you need to use TreeSet instead of HashSet as HashSet doesn't preserve insertion order

5 Comments

no i didn't get it in order, now it changed some other order like four,three,two,five,one
Now also its not in order, now its in some other order..How to use TreeSet
@OneManArmy If it doesn't worked then use LinkedHashSet that should for sure
List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(gnamelist)); Collections.sort(newList,Collections.reverseOrder()); System.out.println("NEWLIST GRADES" + newList); Now also not in ordered...
@OneManArmy don't sor t when you use LinkedHashSet

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.