首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >按值长度对Map<Integer、Map<Integer、Integer>>进行排序

按值长度对Map<Integer、Map<Integer、Integer>>进行排序
EN

Stack Overflow用户
提问于 2022-05-06 15:12:36
回答 1查看 31关注 0票数 1

我想按值长度对Map进行排序。例如,我有以下代码:

代码语言:javascript
复制
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());
    }
}

结果是:

代码语言:javascript
复制
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}

因此,我想要做的是按照值长度对这个Map进行排序,这样它返回:

代码语言:javascript
复制
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}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-05-06 15:24:22

您可以使用流来执行此操作:

代码语言:javascript
复制
var sorted = map.entrySet().stream().sorted(Comparator.comparingInt(it -> it.getValue().size())).toList();

简单地说,您只需要一个定制的Comparator,它将得到一个Map.Entry的值,并比较这个值的size(),在您的例子中,这个值是另一个Map

以下是完整的应用程序:

代码语言:javascript
复制
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);
    }

}

预期产出:

代码语言:javascript
复制
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}]

很明显,精确的输出取决于随机输入.

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72143740

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档