java8对集合的操作等

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_37012236/article/details/79045999

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

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

List<ImportAttributeValue> inserts = groupAttributeValues

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


// 直接获取map中相应的集合,性能很快
        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;


//取商品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使用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的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排序

    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());

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

    二、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值,第三个是指键值映射关系,第四个是指新的容器的实体


    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中


还有诸如 map.containsKey(stringKey),

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

list1.containsAll(list2)



猜你喜欢

转载自blog.csdn.net/qq_37012236/article/details/79045999