Home > OS >  Sort a Map<Integer, Map<Integer, Integer>> by value length
Sort a Map<Integer, Map<Integer, Integer>> by value length

Time:05-07

I want to sort a Map by value length. For example, I have this code:

public static void main(String[] args) {
    Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
    Random random = new Random();

    for (int i = 0; i < 5; i  ) {
        Map<Integer, Integer> mapA = new HashMap<>();
        for (int j = 0; j < random.nextInt(10); j  ) {
            mapA.put(j, j);
        }
        map.put(i, mapA);
    }
    
    for (Map.Entry<Integer, Map<Integer, Integer>> entry:
         map.entrySet()) {
        System.out.println(entry.getKey()   ": "   entry.getValue());
    }
}

and the result is:

0: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5}
1: {}
2: {0=0, 1=1, 2=2, 3=3}
3: {0=0, 1=1, 2=2, 3=3}
4: {0=0, 1=1, 2=2}

so what I want to do is to sort this Map by value length, so it returns:

1: {}
4: {0=0, 1=1, 2=2}
2: {0=0, 1=1, 2=2, 3=3}
3: {0=0, 1=1, 2=2, 3=3}
0: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5}

CodePudding user response:

You can use Streams to do this:

var sorted = map.entrySet().stream().sorted(Comparator.comparingInt(it -> it.getValue().size())).toList();

Basicly you just need a custom Comparator which will get the value of a Map.Entry and compare the size() of that value which in your case is another Map.

Here the full application:

import java.util.*;

public class Application {

    public static void main(String[] args) {
        Map<Integer, Map<Integer, Integer>> map = new HashMap<>();
        Random random = new Random();

        for (int i = 0; i < 5; i  ) {
            Map<Integer, Integer> mapA = new HashMap<>();
            for (int j = 0; j < random.nextInt(10); j  ) {
                mapA.put(j, j);
            }
            map.put(i, mapA);
        }

        for (Map.Entry<Integer, Map<Integer, Integer>> entry:
                map.entrySet()) {
            System.out.println(entry.getKey()   ": "   entry.getValue());
        }
        var sorted = map.entrySet().stream().sorted(Comparator.comparingInt(it -> it.getValue().size())).toList();
        System.out.println(sorted);
    }

}

Expected output:

0: {0=0, 1=1}
1: {0=0, 1=1, 2=2, 3=3, 4=4}
2: {}
3: {0=0}
4: {0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7}
[2={}, 3={0=0}, 0={0=0, 1=1}, 1={0=0, 1=1, 2=2, 3=3, 4=4}, 4={0=0, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7}]

Obviously the exact output depends on the randomized input.

  •  Tags:  
  • java
  • Related