java遍历List和Map的三种常用方法

自定义传参
List<PersonMo> list = new ArrayList<>(Arrays.asList(new PersonMo("ttt","man",11,null)
        ,new PersonMo("AAA","woman",111),new PersonMo("BBB","woman",222)));
Map<Integer,PersonMo> map = new HashMap<>();
map.put(1,new PersonMo("ttt","man",11,null));
map.put(2,new PersonMo("AAA","woman",111));
map.put(3,new PersonMo("BBB","woman",222));

 EntrySet遍历Map

public Map<Integer, PersonMo> EntrySetGetPerson(Map<Integer, PersonMo> personMoMap) {
    for (Map.Entry<Integer,PersonMo> person: personMoMap.entrySet()){
        if (person.getKey() == 1){
            person.setValue(new PersonMo(ReturnMsgConstant.TTT,"superMan",999));
        }
    }
    return personMoMap;
}

 Foreach遍历List

public List<PersonMo> ForEachGetPerson(List<PersonMo> person) {
    person.forEach(e -> {
        if ("ttt".equals(e.getName())){
            e.setName(ReturnMsgConstant.TTT);
        }
    });
    return person;
}

 Stream流遍历List

public PersonMo StreamGetPersonList(List<PersonMo> person) {
        PersonMo personMo = new PersonMo();
        person.stream().forEach(e -> {
            if ("AAssA".equals(e.getName())){
                e.setSex("BigFly");
                BeanUtils.copyProperties(e,personMo);
            }
        });
        return personMo.getName() != null && !personMo.getName().trim().isEmpty() ? personMo :  new PersonMo(ReturnMsgConstant.AAA,"Man",18);
//        return personMo.getName() != null ? personMo :  new PersonMo(ReturnMsgConstant.AAA,"Man",18);
    }

  Stream流遍历Map,返回值分别用Map和List两种方式接

public PersonMo StreamGetPersonMap(Map<Integer, PersonMo> map) {
        PersonMo person;
//        List<PersonMo> personMap = map.entrySet().stream()
//                .filter( e -> "BBB".equals(e.getValue().getName()))
//                .map(Map.Entry::getValue)
//                .collect(Collectors.toList());
//        return personMap.isEmpty() ?  new PersonMo(ReturnMsgConstant.AAA,"Man",18) : personMap.get(0);
        Map<Integer,PersonMo> personMap = map.entrySet().stream()
                .filter( e -> "BBB".equals(e.getValue().getName()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
        for (Map.Entry<Integer,PersonMo> personMo : personMap.entrySet()){
            return personMo.getValue();
        }
        return new PersonMo(ReturnMsgConstant.AAA,"Man",18);
    } 

Gitee地址 : Thwyl/study (gitee.com)

postMan先执行 http://localhost:8008/study/entrySet 方法,把map添加进来,才可实现之后的方法

  • 23
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值