0

I have following HashMap

"1":
   {
    "profilePic":null,
    "roleNo" : "12"
   },
 "2": 
   {
    "profilePic":null,
    "roleNo" : "1"
   }

I want the output as below

   "2":
   {
    "profilePic":null,
    "roleNo" : "1"
   },
 "1": 
   {
    "profilePic":null,
    "roleNo" : "12"
   }

I have tried the below code but didn't get the output as expected

LinkedHashMap<Long, Person> newPerson = attendanceMap
    .entrySet()
    .stream()
    .sorted(Map.Entry.comparingByValue(new AttendanceListComparator()))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

My attendancelistcomparator is as below

@Override
public int compare(Person s1, Person s2) {
    return sortingOrder*s1.getRoleno().compareTo(s2.getRoleno());
}

Please suggest me something to get the sorted data

Yannick Rot
  • 196
  • 2
  • 12
ankit
  • 25
  • 1
  • 2
  • 11

2 Answers2

0

The following code will sort your HashMap entries and store it in a list:

List<Map.Entry<Long, Player>> sorted = mapp.entrySet().stream()
     .sorted(Comparator.comparingLong(Map.Entry::getKey))
     .collect(toList());
xenteros
  • 15,586
  • 12
  • 56
  • 91
0

You have to use sort by value for the map. While sorting by value use 'Roleno' of the Person object. If you want to sort in ascending order of use

o1.getRoleno().compareTo(o2.getRoleno())

otherwise if you want to sort in descending order use

o2.getRoleno().compareTo(o1.getRoleno())

A sample code could be as follows:

private static Map<Long, Person> sortByValueMap(Map<Long, Person> unsortMap) {

    List<Map.Entry<Long, Person>> list = new LinkedList<Map.Entry<Long, Person>>(unsortMap.entrySet());

    Collections.sort(list, new Comparator<Map.Entry<Long, Person>>() {
        public int compare(Map.Entry<Long, Person> o1, Map.Entry<Long, Person> o2) {
            return (o2.getRoleno()).compareTo(o1.getRoleno());
        }
    });


    Map<Long, Person> sortedMap = new LinkedHashMap<Long, Person>();
    for (Map.Entry<Long, Person> entry : list) {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}

Hope this helps. if you have any further queries please write it in comment.

SachinSarawgi
  • 2,632
  • 20
  • 28