3、jdk8-Map集合简单应用

该博客介绍了JDK8中Map集合的基本操作和简单应用,主要基于官方示例进行讲解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本示例主要以官方示例为主

Map集合的简单使用

public class MapTest {
    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("AA",20);
        map.put("BA",30);
        map.put("AB",60);
        map.put("BC",50);
        map.put("EA",70);

        System.out.println("遍历:");
        map.forEach((k,v)->System.out.println(k+"-->"+v));

        Map result = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        Map.Entry::getValue,
                        (oldValue, newValue) -> oldValue,
                        LinkedHashMap::new));//有序集合
        System.out.println("排序Key:"+result);

        Map<String, Integer> result2 = new LinkedHashMap<>();
        map.entrySet().stream()
                .sorted(Map.Entry.comparingByValue())
                .forEachOrdered(e -> result2.put(e.getKey(), e.getValue()));
        System.out.println("排序value:"+result2);

        long count = map.entrySet().stream().filter(entry -> (entry.getKey().contains("B"))).count();
        System.out.println("统计指定值:"+count);


        // 官方的示例:
        //BiConsumer Example
        BiConsumer<String,Integer> printKeyAndValue
                = (key,value) -> System.out.println(key+"-"+value);
        printKeyAndValue.accept("One",1);
        printKeyAndValue.accept("Two",2);

        System.out.println("##################");

        //Java Hash-Map foreach supports BiConsumer
        HashMap<String, Integer> dummyValues = new HashMap<>();
        dummyValues.put("One", 1);
        dummyValues.put("Two", 2);
        dummyValues.put("Three", 3);

        //forEach方法参数就是BiConsumer
        dummyValues.forEach((key,value) -> System.out.println(key+"-"+value));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值