• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

Java8处理List的双层循环

Java处理List的双层循环程序员经常遇到,一般都是当两个List某个值满足某条件时候,进行相应的处理;

1.list和map之间的相互转换;

/**
 * 两个List对象当id相同的时候(注意是两个对象,而非两个集合)
 * @param husbands
 * @param wives
 */
private static void test8(List<Husband> husbands, List<Wife> wives) {
    List<Family> families = Lists.newArrayList();
    //将wives转换为map,这里的key一定要唯一,即为familyId
    Map<Integer, Wife> wifeMap = wives.stream().collect(toMap(w -> w.getFamilyId(), w -> w));
    families = husbands.stream().map(husband -> {
        Family family = new Family();
        Wife wife = wifeMap.get(husband.getFamilyId());
        family.setFamilyId(wife.getFamilyId());
        family.setHusbandName(husband.getHusbandName());
        family.setWifeName(husband.getWifename());
        return family;
    }).collect(Collectors.toList());
}

2.java8中的

groupingBy,
counting,
mapToDouble
filter
sum等函数方法的使用
//苹果颜色对应的数量
Map<String, Long> collect = appleVos.stream().collect(groupingBy(AppleVo::getColor, counting()));
// 过滤掉颜色为黑色的苹果,并汇总好苹果的总金额
Double sum = appleVos.stream().filter(i -> "black".equals(i.getColor())).mapToDouble(AppleVo::getPrice).sum();

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)