Java Tree Map打印值说明

标签 java treemap

我的问题

在打印 map 值时我想打印哪个键有多个值

详情如下

static Map<Integer, Set<String>> myMap = new TreeMap<>();


Key  value
1       a
        b
        c

2       d

3       e

4       f
        g
        h

基于以上 我只想打印 1 和 4 我们需要省略 2 和 3

打印

myMap.entrySet().forEach((e) -> {
                System.out.println(e.getKey());
                e.getValue().forEach((c) -> {
                    System.out.println("    " + c);
                });
            });

最佳答案

您可以应用过滤器

myMap.entrySet().stream().filter(entry -> entry.getValue().size() > 1).forEach...

例如,

public class Test {

    public static void main(String[] args) {
        Map<Integer, Set<String>> myMap = new TreeMap<>();
        Set<String> set1 = new HashSet<>();
        Set<String> set2 = new HashSet<>();
        Set<String> set3 = new HashSet<>();

        set1.add("1");
        set1.add("2");
        set1.add("3");

        set2.add("2");

        set3.add("1");
        set3.add("2");

        myMap.put(1, set1);//3 Elements
        myMap.put(2, set2);//1 Element
        myMap.put(3, set3);//2 Elements

        myMap.entrySet().stream()
             .filter(entry -> entry.getValue() != null)
             .filter(entry -> entry.getValue().size() > 1)
             .forEach(System.out::println);
    }

}

输出

1=[1, 2, 3]
3=[1, 2]

关于Java Tree Map打印值说明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38887277/

相关文章:

java - Elasticsearch - 使用 java api 删除嵌套对象不起作用

Java - 扫描仪错误和打印错误

Java数据结构类似于TreeMap + Hash?

java - 根据字符串键中的标记对 JAVA 映射键进行分组

java - TreeMap "ё"有什么问题?

java - GNU 类路径构建失败

java - 如何从 Java 中的 CopyOnWriteArrayList 中获取底层静态数组?

java - 适用于 iOS 的小数格式

Python 2.6 TreeMap/SortedDictionary?

java - 在大文件Java中查找重复的行