Home > database >  SortList<Employee> inside Map<String, List<Employee>> based on key
SortList<Employee> inside Map<String, List<Employee>> based on key

Time:05-22

I have a List

class Employee{
        String name;
        Integer id;
}

and my list looks like this

[{name:"Satya", id:123},{name:"Andrew", id:125}, {name:"Satya",id:124"}]

now i want to group the above list on names, for which i have written something of this sort.

Map<String, List<Employee>> groupedData = data.stream()
                    .collect(groupingBy(Employee::getName,
                                    LinkedHashMap::new, Collectors.toList()))

So my result looks like this:

{"Satya":[{name:"Satya", id:124}, {name:"Satya", id:123}], "Andrew":[{name:"Andrew", id:125}]}

I want the list to be sorted, the end result should look something like this:

 {"Satya":[{name:"Satya", id:123}, {name:"Satya", id:124}], "Andrew":[{name:"Andrew", id:125}]}

As you can see all the records for every name are sorted based on ID.

CodePudding user response:

You can sort by name, that will also group them, though the actual format is different than what you show.

Collections.sort( data, Employee::getName );

CodePudding user response:

You could sort before collecting, i.e. add stream().sorted(...)

data.stream()
    .sorted(Comparator.comparingInt(Employee::getId))
    .collect(Collectors.groupingBy(Employee::getName, LinkedHashMap::new, Collectors.toList()));
  • Related