-1

I have code like this

List<List<Map<String, String>>> outerList = new ArrayList<>();
List<Map<String, String>> innerList = new ArrayList<>();
outerList.add(innerList)

How to sort outerList using java8 based on the map values. I do not want the inner list to be sorted.

Example:

List<Map<String, String>> innerList1 = new ArrayList<>(); 
Map<String, String> map1= new HashMap<String, String>();
map1.put("sort", "2")
innerList1.add(map1);

List<Map<String, String>> innerList2 = new ArrayList<>(); 
Map<String, String> map2 = new HashMap<String, String>();
map2.put("sort", "1")
innerList2.add(map2);

outerList.add(innerList1);
outerList.add(innerList2);

after sorting the innerList2 should be first in the list and innerlist1 should be second Since the sort value is 2 and 1;

1 Answers1

0

Assuming sorting based on 1st element of outerList and "sort" key of map

below lambda expression will work for you.

List<List<Map<String, String>>> collect = outerList.stream().sorted((e1, e2) -> e1.get(0).get("sort").compareTo(e2.get(0).get("sort"))).collect(Collectors.toList());

Without Streams:

outerList.sort((e1, e2) -> e1.get(0).get("sort").compareTo(e2.get(0).get("sort")));

With comparator:

outerList.sort(new Comparator<List<Map<String,String>>>() {
        @Override
        public int compare(List<Map<String, String>> e1, List<Map<String, String>> e2) {

        <your logic here>
            return <int value>;
        });
Rahul Jain
  • 1,319
  • 7
  • 16