java8对集合的操作等

我们在操作集合时,可能会遇到很多复杂的业务逻辑,这时候可能会嵌套n层循环来实现逻辑功能,但是我们用java8的lambda来操作集合的话相比较来说会肥肠简单:

//选取符合一定条件的新list

List<ImportAttributeValue> inserts = groupAttributeValues

.stream()
.filter(it -> !groupBaseAttributes.containsKey(it.getAttributeName()))
.collect(Collectors.toList());

 

// 直接获取List中相应的集合,性能很快
        List<Long> target = categories.get(level);
        // 根据父类目获取相应的子类目信息,之前写好的方法
        List<CategoryResult> children = getPlatformCategoryByParentId(platformId, parentCategoryId);
        List<CategoryResult> result = children.stream()
                // 子类目中筛选相应的审核通过的类目,包含其类目ID信息
                .filter(it -> target.contains(it.getCid()))
                // 聚合成集合进行返回
                .collect(Collectors.toList());
        return result;

 

// 将DtoList转换为Volist
        List<HistoryDto> resultList = page.getList().stream().map(entity -> {
                    HistoryDto dto = new HistoryDto();
                    BeanUtils.copy(entity, dto);
                    return dto;
                }).collect(Collectors.toList());

 

//取商品ID集合(为批量查询商品销量做准备)
        if (retList != null && retList.size() > 0){
            itemIds = retList.stream()
                    .map(it -> it.getItemId())
                    .collect(Collectors.toList());

        }

 

        List<Long> picSkus = list.stream()
                .map(it -> it.getSkuId())
                .distinct()
                .collect(Collectors.toList());

 

//过滤之后组装新list然后再遍历

platformCategoryAttributeList.parallelStream()
                .filter(it -> attrIdList.contains(it.getId()))
                .collect(Collectors.toList())
                .parallelStream()
                .forEach(it -> {
                    Map<String,Object> column = new HashedMap();
                    column.put("id", it.getAttrId());
                    column.put("name",it.getAttrName());
                    columnAttributeList.add(column);
                });

 

//循环运行多条语句,函数式forEach

platformCategoryAttribute.getPlatformCategoryAttributeValues()

.stream()

.forEach(it -> {

it.setAttrId(platformCategoryAttribute.getId());

it.setAttrValueId(it.getId());

}

);

 

//List  的 addAll 的方法 (取两个list 的并集)

listA.addAll(listB)

首先两边都不允许为null

但是允许两边为size等于0的实例,也会进行取并集操作

 

//过滤并取得符合相应条件的对象

ShopItemAnnex itemPicture = shopItemAnniceList.stream()
                .filter(it -> 1 == it.getSortNumber())
                .findFirst()
                .get();

 

//下面介绍一下一个对集合进行判断的方法

hasInventory = !skuInventoryList.stream()
                    .anyMatch(it -> (null == it || it < 1));

此方法返回布尔值,只要满足其中一个就会返回true,当然还有allMatch方法,全部满足才会返回true

 

//下面介绍讲List转化为Map的方法

Map<Long, String> collect = itemList.stream().collect(HashMap::new, (m,v)->m.put(v.getId(), v.getItemName()), HashMap::putAll);

此方法是讲item对象集合中的id与itemName转化为map集合,允许重复的键,也允许value中存在null值,但是Collectors.toMap方法不允许有重复的键,也不允许有value为null,向下面代码,我们需要做多余的代码来判断重复与null, Map<Long, String> result = items.stream().collect(Collectors.toMap(Item::getId, Item::getItemName, (key1, key2) -> key2, TreeMap::new));

Map<Long, ItemSkuPictureVo> collect = itemSkuPictureVoList.stream().filter(it -> null != it.getSkuId())

                    .collect(Collectors.toMap(ItemSkuPictureVo::getSkuId, it -> it, (x, y) -> x));


Map<Long, ShopItemSku> skuMap = itemSkus.stream()

                .collect(Collectors.toMap(ShopItemSku::getId, it -> it));

 

//下面介绍根据list对象某个字段去重

Collection<SoRepairTriggerBill> values = soInfo.stream()
                .filter(it -> StringUtils.isNotEmpty(it.getRepairecode()))
                .collect(Collectors.toMap(it -> it.getRepairecode(), it -> it, (x, y) -> y))
                .values();

 

注:list使用Collectors.toMap转换为map  若key值相同时处理,使用函数来选择比较使用旧值还是新值

List<PlatformCategoryAttributeValue> origin = null

logger.info("排重店铺的销售属性值问题:{}", origin);
        BinaryOperator<PlatformCategoryAttributeValue> operator = (existingValue, newValue) ->{
            // 当key重复时候,使用平台值
            if(new Integer(1).equals(existingValue.getFromType())) {
                return existingValue;
            }
            return newValue;
        };

        Map<String, PlatformCategoryAttributeValue> mapResult = origin.stream()
                .collect(Collectors.toMap(PlatformCategoryAttributeValue::getAttrValueName, it-> it, operator));

 

 

//对于map的循环

mapping.forEach((k, v) -> {
            if(!result.containsKey(k)) {
                inserts.add(v);
            }
        });

 

//下面是讲List中对象的Integer字段求和的方法

List<Integer> numList = Arrays.asList(100, 200, 300, 400, 500);

Double aDouble = numList.stream().map((cost2) -> cost2 + .12 * cost2).reduce((a, b) -> a + b).get();

 

//对字符串的去重可以用有序set与lambda来解决,拼接集合某字段为String

String str = "whwhkknkn9hg59";

String[] split = str.split("");
String distinctStr = Arrays.stream(split).distinct().collect(Collectors.joining(""));

 

//获取List中数字的最小值、最大值、总和以及平均值
List<Integer> primes = Arrays.asList(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println("最大值是 : " + stats.getMax());
System.out.println("最小值是 : " + stats.getMin());
System.out.println("求和是 : " + stats.getSum());
System.out.println("求平均数为 : " + stats.getAverage());

输出:
最大值是 : 29
最小值是 : 2
求和是 : 129
求平均数为 : 12.9

//下面介绍List的retailAll()方法

list3.retainAll(list1)

首先, 这个retainAll 方法的作用是 :
java.util.ArrayList.retainAll(Collection<?> collection)
仅保留此collection中那些也包含在指定collection的元素(可选操作)。
换句话说,移除此collection中未包含在指定collection中的所有元素。
此实现在此collection上进行迭代,依次检查该迭代器返回的每个元素,以查看其是否包含在指定的

collection中。如果不是,则使用迭代器的remove方法将其从此collection中移除。
返回值的意思是这样的,如果此 collection 由于调用而发生更改,则返回 true

在此,你这个list3 和list1 里面元素的内容 其实是一样的, 这样一来,调用 list3.retainAll(list1) 时候
,发现,不需要从list3中去除不在list1中的元素,因此这个list3不需要发生更改,那么返回值就是是
false,也就是说,这个方法的返回值是标识list3 有没有改变,而不是这个方法是否执行正常或者成功

JDK1.6 这个方法的 源码
public boolean retainAll(Collection<?> c){
    boolean modified = false;
    Iterator<E> e = iterator();
    while (e.hasNext()){
        if (!c.contains(e.next())){
            e.remove();
            modified = true;
        }
    }
    return modified;

}

//集合的排序

    第一种实现Comparator接口,实现compare方法来进行排序
    //排序List<Obiect>
    private List<PlatformCategoryAttribute> sort(List<PlatformCategoryAttribute> platformCategoryAttributes) {

        Collections.sort(platformCategoryAttributes, new Comparator<PlatformCategoryAttribute>() {
            @Override
            public int compare(PlatformCategoryAttribute o1, PlatformCategoryAttribute o2) {
                Long i = o1.getAttrId() - o2.getAttrId();
                return i.intValue();
            }
        });
        for (PlatformCategoryAttribute platformCategoryAttribute : platformCategoryAttributes){
            List<PlatformCategoryAttributeValue> values = platformCategoryAttribute.getPlatformCategoryAttributeValues();
            if (values != null && values.size() > 1){
                Collections.sort(values, new Comparator<PlatformCategoryAttributeValue>() {
                    @Override
                    public int compare(PlatformCategoryAttributeValue p1, PlatformCategoryAttributeValue p2) {
                        Long ii = p1.getAttrValueId() - p2.getAttrValueId();
                        return ii.intValue();
                    }
                });
            }
        }
        return platformCategoryAttributes;
    }

    注:属性id和属性值id是一对多的关系

 

下面是java8对于集合的排序:

    一、list排序

    1)、List<Integer> list = Arrays.asList(new Integer[]{1,9,4,6,2,7,5,3});  //构造list,填充值

    list  = list .stream().sorted((n1,n2)->n1.compareTo(n2)).collect(Collectors.toList());

internalItemDtos.stream().sorted(Comparator.comparing(InternalItemDto::getSort,Comparator.nullsLast(Long::compareTo))).collect(Collectors.toList());//nullsLast可预防空指针

    "->"左边是入参,右边是具体的比较操作,然后将结果通过collect返回.

   list.stream().filter(bean-> !StatusEnum.CELLED.getCode().equalsIgnoreCase(bean.getStatus()))
                .sorted((beanA,beanB)->{
                    String bNo = beanA.getBNo();
                    String bNoB = beanB.getBNo();
                    boxNo = boxNo == null ? "":boxNo;
                    boxNoB = boxNoB == null ? "":boxNoB;
                    int i = bNo.compareTo(bNoB);
                    if(i!=0){
                        return i;
                    }
                    String pPn = beanA.getPPn();
                    String pPnB = beanB.getPPn();
                    pPn = pPn == null ? "":pPn;
                    pPnB = pPnB == null ? "":pPnB;
                    return pPn.compareTo(pPnB);
                })
                .collect(Collectors.toList());

   2)、判断集合是否包含

    还有诸如 map.containsKey(stringKey),

    list1.contains(object1),注:(注意需要重写equals方法)

    list1.containsAll(list2)

    二、map排序

    Map<String, Integer> unsortMap = new HashMap<>();
    unsortMap.put("z", 10);
    unsortMap.put("b", 5);
    unsortMap.put("a", 6);
    Map<String, Integer> result2 = new LinkedHashMap<>();

    List<ItemBrandVo> finalList= new ArrayList<>();

    2)、Map<String, Integer> result = unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                 (oldValue, newValue) -> oldValue, LinkedHashMap::new));

   将map(HashMap)对象包装成 Stream 后调用.sorted排序,通过Key值比较,然后用.collect收集为LinkedHashMap,此重载收集器一共四个参数,第一值是指key值,第二个是指value值,第三个是指键值映射关系,第四个是指新的容器的实体

  三、语法糖示例、

    //
    List<ItemBrandVo> itemBrandVoListLetter = new ArrayList<>();
                List<ItemBrandVo> finalMap = new ArrayList<>();
                Map<String, List<ItemBrandVo>> letterListMap = itemBrandVoListLetter.stream()
                    .collect(Collectors.groupingBy(ItemBrandVo::getInitial));
letterListMap.entrySet().stream()
                    .sorted(Map.Entry.<String, List<ItemBrandVo>>comparingByKey())
                    .forEachOrdered(e -> e.getValue().forEach(finalMap::add));

   //

   List<JsonUtils.SimpleAttrValue> sorted = simpleAttrValues.stream().sorted(Comparator.comparing(JsonUtils.SimpleAttrValue::getAid)).collect(Collectors.toList());
                return JsonUtils.toJSONString(sorted);

    

  // 根据某个属性分组计数
        Map<String,Long> result1=list1.stream().collect(Collectors.groupingBy(Student::getGroupId,Collectors.counting()));

 

    2)、unsortMap.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> result2.put(x.getKey(), x.getValue()));
    将map(HashMap)对象包装成 Stream 后调用.sorted排序,通过Key值比较,然后将每一组键值对进行相应.forEachOrdered操作,此处是将每一组的键和值重新装入新的结果中(LinkedHashMap)

 

    3)、specialListMap.entrySet().stream()
                    .sorted(Map.Entry.<String, List<ItemBrandVo>>comparingByKey())
                    .forEachOrdered(e -> e.getValue().forEach(finalMap::add));
    将map(HashMap)对象包装成 Stream 后调用.sorted排序,通过Key值比较,然后将每一组键值对进行相应.forEachOrdered操作,此处是将每一组的值重新装入finalList中

 

注意事项:我们在初始化HashMap的时候可以指定加载因子:

 HashMap aaa = new HashMap(50000);

 当你的加载因子指定超过一万时性能会有很大的影响,如果超过万时会有秒级的影响,如果过大时无法初始化,会直接抛出内存溢出异常,当然一般不会指定太大,一般10以内足以,不指定默认情况下的话是0.75,代表了满75位自动扩展

 

 

http://outofmemory.cn/java/java8-lambda-expression-example

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值