JAVA stream流常用操作整理

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

 stream流处理:将以逗号拼接的字符串分隔,并转换成特定类型的list

List<Long> idList = Arrays.stream(stringExample.split(","))
.map(String::trim)
.map(Long::parseLong)
.collect(Collectors.toList());


 stream流处理:将list转换成以逗号分隔的字符串

String result = similarIdList.stream()
.map(Object::toString)
.collect(Collectors.joining(Constants.COMMA)); 

stream流处理:统计list中某一属性相同的个数,并转换成map

Map<String, Long> skuNumberMap =list.stream().collect(Collectors.groupingBy(DTO::getWarehouseCode, Collectors.counting()));

stream流处理:统计list中某一属性相同的item,并累加item的另一属性作为value,并转换成map

Map<String, Integer> groupedMap = list.stream().collect(Collectors.groupingBy(DTO::getDapCode,
Collectors.summingInt(DTO::getDapGoodsQty)));

stream流处理:统计list中item某一属性的总和

int res= dapCountList.stream().mapToInt(DTO::getCount).sum();

stream流处理:将list根据某一个属性进行排序


//根据某一属性倒序排列
list= list.stream().sorted(Comparator.comparing(
                            DTO::getPriceVerificationStatus).reversed()).collect(Collectors.toList());

//根据某一属性正序排列
list= list.stream().sorted(Comparator.comparing(
DTO::getPriceVerificationStatus)).collect(Collectors.toList());

 stream流处理:将list根据先某一个属性进行排序,再根据另一个属性进行排序

List<DTO> resList = list.stream().sorted(Comparator.comparing(DTO::getInventory).reversed()
                        .thenComparing(DTO::getWarehouseCode)).collect(Collectors.toList());

stream流处理:将list根据某一个属性进行去重

ArrayList<DTO> collect = resultList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
new TreeSet<>(Comparator.comparing(DTO::getSalesGoodsCode))), ArrayList::new));

 对于一些特殊规则的排序   可以定义比较器进行比较【比如将状态根据2,3,1的顺序进行排序】

然后再根据订单号的字典顺序进行排序

        Comparator<BatchUpdateStatusDetail> customBComparator = Comparator.comparingInt(a -> {
            switch (a.getConclusion()) {
                case 2: return Constants.ZERO;
                case 3: return Constants.ONE_INT;
                case 1: return Constants.TWO_INT;
                default: throw new IllegalArgumentException("Unknown b value: " + a.getConclusion());
            }
        });
        List<BatchUpdateStatusDetail> sortedList = list.stream()
                .sorted(customBComparator.thenComparing(BatchUpdateStatusDetail::getSalesOrderNumber))
                .collect(Collectors.toList());

将list类型的属性不为空的排在前面,然后再根据订单号进行排序

//将有tag的订单排在前面
 List<BatchUpdateStatusFileDTO> theResList = list.stream().sorted(Comparator
    .<BatchUpdateStatusFileDTO>comparingInt(a -> !a.getTagList().isEmpty() ? 0 : 1)
    .thenComparing(BatchUpdateStatusFileDTO::getSalesOrder))
    .collect(Collectors.toList());

stream流处理:list根据整体 item 去重

list.stream().distinct().collect(Collectors.toList());

stream流处理:list转为string,用逗号分隔【该方法对list的泛型有限制】

String res= list.stream().map(String::valueOf).collect(Collectors.joining(","));

stream流处理:统计list中的元素是否都满足特定条件   都不满足  有一个满足   返回布尔类型

//有一个满足
list.stream().anyMatch(r -> CollUtil.isEmpty(r.getDapIdList()))

//没有一个满足
list.stream().noneMatch(r -> CollUtil.isEmpty(r.getDapIdList()))

//全部都满足
list.stream().allMatch(r -> CollUtil.isEmpty(r.getDapIdList()))

stream流处理:将二维的list转换成一维的list , 或者是将value为list的map  取出全部value转换成一个新的list

Java StreamflatMap方法‌是一种中间操作,用于将流中的每个元素转换成一个流,然后将这些流中的元素合并成一个新的流。这个方法特别适用于处理嵌套的集合结构,如List<List>;Stream<Stream>;,并将它们转换成一个扁平的流。

List<List<Integer>> listOfLists = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5), Arrays.asList(6, 7, 8));
List<Integer> flattenedList = listOfLists.stream().flatMap(list -> list.stream()).collect(Collectors.toList());

stream流处理:计算总金额,并乘上数量

BigDecimal total = Stream.of(
DTO.getSalesGoodsUnitTaxPrice(),
DTO.getSalesGoodsGiftTaxPrice(),
DTO.getSalesGoodsShippingTaxPrice(),
DTO.getSalesGoodsHandlingTaxPrice()
).map(tax -> tax.multiply(qty))
.reduce(BigDecimal.ZERO, BigDecimal::add);

//stream.reduce  求和 设置0为初始值

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int sum = list.stream().reduce(0, (a, b) -> a + b);

List<Integer> list = Collections.emptyList();
int sum = list.stream().reduce(0, (a, b) -> a + b); // 返回0,因为初始值为0

//stream.reduce 求积 设置1为初始值

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int product = list.stream().reduce(1, (a, b) -> a * b);


//stream.reduce  求最大值
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> max = list.stream().reduce(Integer::max);

stream流将list先根据一个属性分组,再根据另一个属性进行分组

public static void main(String[] args) {
        List<Item> items = Arrays.asList(
                new Item("Fruit", "Red"),
                new Item("Fruit", "Green"),
                new Item("Vegetable", "Green"),
                new Item("Fruit", "Red"),
                new Item("Vegetable", "Yellow")
        );
        //先根据种类进行分组  在同种类中,再根据颜色进行分组
 
        Map<String, Map<String, List<Item>>> grouped = items.stream()
                .collect(Collectors.groupingBy(
                        Item::getType,
                        Collectors.groupingBy(
                                Item::getColor
                        )
                ));
 
    }

stream流使用peek()对list中的item进行操作,再根据另外两个属性进行去重,得到去重以后得list

            theLastListNoBoxId = new ArrayList<>(theLastListNoBoxId.stream()
                    .peek(a -> {
                        a.setItemCode(a.getDapItemCode());
                    }).collect(Collectors.toMap(
                            item -> item.getSoHeadId() + ":" + item.getSodiLineId(), // 创建唯一键
                            item -> item, // 映射到值(即原对象)
                            (existing, replacement) -> existing // 选择第一个遇到的元素作为值(去重)
                    )).values()); // 转换回List

您可能感兴趣的与本文相关的镜像

Python3.8

Python3.8

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值