Guest User

Untitled

a guest
Aug 14th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. Sorting hashmap by values
  2. HashMap<Integer,String> map = new HashMap<Integer,String>();
  3. map.put("1",froyo);
  4. map.put("2",abby);
  5. map.put("3",denver);
  6. map.put("4",frost);
  7. map.put("5",daisy);
  8.  
  9. 2,abby;
  10. 5,daisy;
  11. 3,denver;
  12. 4,frost;
  13. 1,froyo;
  14.  
  15. public LinkedHashMap sortHashMapByValuesD(HashMap passedMap) {
  16. List mapKeys = new ArrayList(passedMap.keySet());
  17. List mapValues = new ArrayList(passedMap.values());
  18. Collections.sort(mapValues);
  19. Collections.sort(mapKeys);
  20.  
  21. LinkedHashMap sortedMap =
  22. new LinkedHashMap();
  23.  
  24. Iterator valueIt = mapValues.iterator();
  25. while (valueIt.hasNext()) {
  26. Object val = valueIt.next();
  27. Iterator keyIt = mapKeys.iterator();
  28.  
  29. while (keyIt.hasNext()) {
  30. Object key = keyIt.next();
  31. String comp1 = passedMap.get(key).toString();
  32. String comp2 = val.toString();
  33.  
  34. if (comp1.equals(comp2)){
  35. passedMap.remove(key);
  36. mapKeys.remove(key);
  37. sortedMap.put((String)key, (Double)val);
  38. break;
  39. }
  40.  
  41. }
  42.  
  43. }
  44. return sortedMap;
Add Comment
Please, Sign In to add comment