Java学习

Java Map常用操作记录

2020-08-05  本文已影响0人  xiaogp
        // 增加元素
        Set<String> aa = new HashSet<>();
        aa.add("a");
        aa.add("b");
        aa.add("a");
        aa.add("c");
        System.out.println(aa);

        // 创建一个带有初始元素的集合
        Set<String> cc = new HashSet<String>() {
            {
                add("a");
                add("b");
                add("c");
            }
        };
        System.out.println("cc " + cc);

        Set<String> dd = new HashSet<>(Arrays.asList("c", "b", "a"));
        System.out.println("dd " + dd);

        // 删除元素
        aa.remove("c");
        System.out.println(aa);

        // 移除所有元素
        aa.clear();
        System.out.println(aa);

        // 集合元素遍历
        for (String a : aa) {
            System.out.println(a);
        }

        Iterator<String> iter = aa.iterator();
        while (iter.hasNext()) {
            System.out.println(iter.next());
        }

        // 集合大小
        System.out.println(aa.size());

        // 判断元素是否存在
        System.out.println(aa.contains("a"));

        // 添加多个元素
        aa.addAll(Arrays.asList("a", "b", "c"));
        // addAll接受的参数collection, Arrays需要先转化为collection
        aa.addAll(Arrays.asList("d,e,f".split(",")));

        // 交集
        Set<String> q = new HashSet<String>() {
            {
                add("a");
                add("b");
                add("c");
            }
        };

        Set<String> w = new HashSet<>(Arrays.asList("c", "b", "d"));
        System.out.println(q);
        System.out.println(w);
        // 新建一个空集合
        Set<String> e = new HashSet<>();
        e.addAll(q);
        e.retainAll(w);
        System.out.println("交集: " + e);

        // 并集
        e.clear();
        e.addAll(q);
        e.addAll(w);
        System.out.println("并集: " + e);

        // 差集
        e.clear();
        e.addAll(q);
        e.removeAll(w);
        System.out.println("差集: " + e);  // [a]

        e.clear();
        e.addAll(w);
        e.removeAll(q);
        System.out.println("差集:" + e);  // [d]

        System.out.println("-----------------------");
        // 测试HashMap
        Map<String, Integer> abc = new HashMap<>();
        // 插入元素
        abc.put("a", 1);
        abc.put("b", 2);
        System.out.println(abc);

        // 创建带有初始元素的字典
        Map<String, Double> cba = new HashMap<String, Double>() {
            {
                put("a", 1.0);
                put("b", 2.5);
                put("c", 1.5);

            }
        };
        System.out.println(cba);

        // 删除元素
        abc.remove("a");
        System.out.println(abc);

        // 查找元素
        int tmp = abc.getOrDefault("a", 5);
        System.out.println(tmp);

        // 转化为映射对遍历
//        Map中采用Entry内部类来表示一个映射项,映射项包含Key和Value
//        Map.Entry里面包含getKey()和getValue()方法
        for (Map.Entry<String, Double> items : cba.entrySet()) {
            System.out.println(items.getKey());
            System.out.println(items.getValue());
        }

        // 使用forEach遍历
        System.out.println("使用forEach");
        cba.forEach((k, v) ->
        {
            System.out.println(k);
            System.out.println(v);
        });

        // 根据value进行排序
        System.out.println("排序");
        List<Map.Entry<String, Double>> list = new ArrayList<>(cba.entrySet());
        System.out.println(list);  // [a=1.0, b=2.5, c=1.5]
        Collections.sort(list, new Comparator<Map.Entry<String, Double>>() {
            @Override
            public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) {
                return o1.getValue().compareTo(o2.getValue());  // 升序  [a=1.0, c=1.5, b=2.5]
                //return o2.getValue().compareTo(o1.getValue())  // 降序
            }
        });
        System.out.println(list);
        // 排序之后取前几
        System.out.println("排序之后取前几");
        List<String> list_rank = list.stream().map(x -> x.getKey()).collect(Collectors.toList()).subList(0, 2);
        System.out.println(list_rank);

        // 判断key是否存在
        System.out.println("判断key是否存在");
        System.out.println(cba.containsKey("a"));

        // 查看字典元素个数
        System.out.println(cba.size());

        // 字典值更新
        Map<String, Integer> incMap = new HashMap<>();
        for (String i : "a,b,c,a,c,f,r,d,s,s,c".split(",")) {
            incMap.put(i, incMap.getOrDefault(i, 0) + 1);
        }
        System.out.println(incMap);
        // {a=2, b=1, r=1, c=3, s=2, d=1, f=1}

        // 多层嵌套字典
        Map<String, Map<String, Integer>> incMap2 = new HashMap<>();
        for (String i : "a,b,c,a".split(",")) {
            for (String j : "a,b,c,a".split(",")) {
                if (!incMap2.containsKey(i)) {
                    incMap2.put(i, new HashMap<String, Integer>());
                }
                incMap2.get(i).put(j, incMap2.get(i).getOrDefault(j, 0) + 1);

            }
        }
        System.out.println(incMap2);

merge操作

字典合并, 新的key无则插入, 有则根据条件更新, 相当于对字典的key做聚合操作

class EntInfo {
    private String name;
    private double score;

    public EntInfo(String name, double score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }
}
public static void mapMergeTest() {
        Map<String, Double> a = new HashMap<>();
        List<EntInfo> b = new ArrayList<>();
        b.add(new EntInfo("a", 23.0));
        b.add(new EntInfo("b", 24.3));
        b.add(new EntInfo("a", 25.7));
        b.add(new EntInfo("a", 21.3));
        b.add(new EntInfo("b", 21.0));

        // (o, n) 是Map的value,就是第二个参数s.getScore()
        // 如果出现key冲突, 比value大小
        b.forEach(s -> a.merge(s.getName(), s.getScore(), (o, n) -> o > n ? o : n));
        System.out.println(a);  // {a=25.7, b=24.3}

        // 如果出现冲突, 将value字符串拼接
        Map<String, String> c = new HashMap<>();
        b.forEach(s -> c.merge(s.getName(), String.valueOf(s.getScore()), (o, n) -> o + "_" + n));
        System.out.println(c);

        // 更加自由的指定key和value
        Map<String, Map> d = new HashMap<>();
        b.forEach(s -> d.merge(s.getName(), new HashMap<String, Double>() {{
            put(s.getName(), 1.0);
        }}, (o, n) -> n));
        System.out.println(d);

        // 在第三个参数中加入return代码块
        Map<String, Map> e = new HashMap<>();
        b.forEach(s -> e.merge(s.getName(), new HashMap<String, Double>() {{
            put(s.getName(), 1.0);
        }}, (o, n) -> {
            o.put(s.getName(), o.get("" + s.getName()) + "," + n.get(s.getName()));
            return o;
        }));
        System.out.println(e);  // {a={a=1.0,1.0,1.0}, b={b=1.0,1.0}}

    }
上一篇 下一篇

猜你喜欢

热点阅读