java函数使用笔记(二)

一、Optional流

Optional类型用来检查是否为空,确保流不会中断。

1、isPresent 是否不为空,不为空-true; 空-false

2、isEmpty 是否为空,不为空-false; 空-true

Arrays.stream(orderList)
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .orElse("未知订单类名称")

3、orElse 为空情况,为空时候给固定值

4、orElseGet 为空时候给个函数,构造默认值

Arrays.stream(orderList)
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .orElseGet(()->"anonymous");//"anonymous"常量,.orElseGet()工厂
assertNotNull(orderTypeName);
assertEquals("anonymous",orderTypeName);

5、orElseThrow 为空时候抛出异常

6、or 继续返回Optional

7、ifPresent 有值时候的处理

Arrays.stream(orderList)
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .ifPresent(orderTypeName->{
            log.debug("orderTypeName{}",orderTypeName);
            assertEquals("文具",orderTypeName);

        })

8、ifPresentOrElse 有值无值都要处理

Arrays.stream(orderList)
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .ifPresentOrElse(
            orderTypeName->{
                log.debug("orderTypeName{}",orderTypeName);
                assertEquals("文具",orderTypeName);
            },
            ()->{
                log.dubug("订单类名称为空");
            }

        )

二、Collectors收集器

toList

Set<String> orderTypeNames = orderList.stream()
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .collect(toList());

toSet

Set<String> orderTypeNames = orderList.stream()
        .filter(order->!"玩具".equals(orderTypeName))
        .findAny()
        .map(Order::orderTypeName)
        .collect(toSet());

toMap

Map<String,Order> orderMap = orderList.stream()
        .collect(toMap(
            Order::getOrderTypeNames,
            order->order
        ));
assertTrue(orderMap.containsKey("玩具"))

//合并
TreeMap<String,Order> orderMap = stream().concat(orderList.stream(),orderList.stream())
        .collect(toMap(
            Order::getOrderTypeNames,
            order->order,
            (existing, replace)->existing,
            TreeMap::new
        ));
assertTrue(orderMap.containsKey("玩具"))

toCollection

三、分组统计、聚合函数和其他操作符

1、聚合计算

averagingXXX 、  summingXXX 、 maxBy、 counting 

//按价格取平均数、求和  价格={23,26,50}
double avg = orderList.stream().collect(averagingDouble(Order::getPrice));
double sum = orderList.stream().collect(summingInt(Order::getPrice));
//公共方法DoubleSummaryStatistics,包括求和、平均数、最大值、最小值等
DoubleSummaryStatistics stat = orderList.stream().collect(summarizingDouble(Order::getPrice));
assertEquals((23+26+50),stat.getSum());

2、分组统计

groupingBy

//分组 10一个价格段 例如:20、21为一组
val result : Map<Integer,List<Order>> = orderList.stream()
                .collect(groupingBy(order->(int)Math.floor(order.getPrice() / 10)));

//两个参数例子,取每组的平均数、和、最大值、最小值等
val result : Map<Integer,DoublSummaryStatistics> = orderList.stream().collect(
                       groupingBy(
                            order->(int)Math.floor(order.getPrice() / 10),
                            summarizingDouble(Order:getPrice)
                       )
);

 3、其他操作符

mapping

//mapping做类型转换
val result : Map<Integer,List<OrderDto>> = orderList.stream().collect(
                       groupingBy(
                            order->(int)Math.floor(order.getPrice() / 10),
                            mapping(order->new orderDto(
                                        order.getOrderId(),
                                        name:order.getOrderTypeName()
                            ),
                            toList()
                        )       
)

collectingAndThen

//计算价格的平均值,使用.collectingAndThen可在Collectors中做数据处理
Double avgPrice = orderList.stream()
            .collect(
                Collectors.collectingAndThen(
                    Collectors.averagingDouble(Order::getPrice), 
                    Double::doubleValue
                )
            );
System.out.println(avgPrice);

joining

// 输出==》 name1 的结果:玩具文具厨具
String name1 = orderList.stream()
                        .map(Order::getOrderTypeName)
                        .collect(Collectors.joining());
System.out.println("name1 的结果:" + name1 ); 

// 输出==》 name2 的结果:玩具,文具,厨具
String name2 = orderList.stream()
                        .map(Order::getOrderTypeName)
                        .collect(Collectors.joining(“,”));
System.out.println("name2 的结果:" + name2 ); 

// 输出==》name3 的结果:{玩具,文具,厨具}
String name3 = orderList.stream()
                        .map(Order::getOrderTypeName)
                        .collect(Collectors.joining(",", "{", "}"));
                        //前缀是"{",后缀是"}",中间用","分隔的字符串
System.out.println("name3 的结果:" + name3 ); 

 四、排序

sorted可以传入Comparator

List<String> list = Arrary.asList("aaa","bbb","ccc");
//正序
val abc = list.stream().sorted(String::comparaTo).collect(toList());
val abc = list.stream().sorted(Comparator.naturalOrder()).collect(toList());
//倒叙
val abc = list.stream().sorted(Comparator.reverseOrder()).collect(toList());

//按某字段排序 写法一
val abc = list.stream()
                .sorted(
                    (a,b)->order.getOrderId().ComparaTo(order.getOrderId())
                )
                .collect(toList());
//按某字段排序 写法二
val abc = list.stream()
                .sorted(Comparator.comparaing(
                        order->order.getOrderId(),
                        (a,b)->a.ComparaTo(b)
                    )
                )
                .collect(toList());

五、高级操作符flatMap——处理流的嵌套

1、父类对象常见的集合属性

//订单表
private static final Order[] arraryOrder = {
    Order.builder()
            .id("1L")
            .orderCode("202206200001")
            .orderTyprName("玩具")
            .price(20.00)
            .color(List.of("黄色","红色"))
            .build(),
    Order.builder()
            .id("2L")
            .orderCode("202206200002")
            .orderTyprName("文具")
            .price(10.00)
            .color(List.of("粉色",“蓝色”))
            .build(),
    Order.builder()
            .id("3L")
            .orderCode("202206200003")
            .orderTyprName("厨具")
            .price(80.00)
            .color(List.of("黑色"))
            .build()
};

//使用map   
val orders= orderList.stream()
                    .map(Order::getColor)
                    .peek(color->log.debug("color{}",color))
                    .collect(toList());
log.debug(“orders:{}”,orders);//输出=>> orders:[[黄色,红色,蓝色],[粉色,蓝色],[黑色]]

//使用flatMap    嵌套——父类对象常见的集合属性
val orders= orderList.stream()
                    .flatMap(order->user.getColor().stream)
                    .peek(color->log.debug("color{}",color))
                    .collect(toList());
log.debug(“orders:{}”,orders);//输出=>> orders:[黄色,红色,粉色,蓝色,黑色]
                    

2、在流中产生了Optional元素

//嵌套——在流中产生了Optional元素
val profiles= orderList.stream()
                    .map(order->ThirdPartyApi.findByOrderTypeName(order.getOrderTypeName))
                    .flatMap(Optional::stream)//Optional空值的结果会去掉,
                    .peek(profile->log.debug("profile:{}",profile))
                    .collect(toList());
log.debug(“profiles:{}”,profiles);//输出=>> profiles:[[黄色,红色,蓝色],[粉色,蓝色],[黑色]]




六、reduce

执行归集操作,类似于Collect

//累加  初始值为0  累加器
Interger sum = orderList.stream()
                        .map(Order::getPrice)
                        .reduce(0,(Interger a, Interger b)->Interger.sum(a,b))

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的List函数是一个接口,用于表示有序集合或序列。List接口的实现类有ArrayList、LinkedList和Vector。其中,ArrayList是可变数组,LinkedList是链接列表,Vector是线程安全的可变数组。 List接口提供了一些常用的函数,比如add(E e)用于将指定的元素追加到列表的末尾,size()用于返回列表中的元素数,get(int index)用于返回指定位置的元素。另外,List接口还提供了addAll(int index, Collection<? extends E> c)函数,用于将指定集合中的所有元素插入到列表的指定位置。 下面是一个使用ArrayList的示例代码: ```java import java.util.ArrayList; public class ListTest { public static void main(String\[\] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); // 遍历列表的元素 for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } ``` 这段代码创建了一个ArrayList对象,然后使用add()函数将元素添加到列表中,最后使用get()函数遍历列表的元素并打印出来。 #### 引用[.reference_title] - *1* *2* [JAVA——34.集合函数-List](https://blog.csdn.net/zhaiyujia15195383763/article/details/81089397)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Java中List接口学习笔记(常用函数)](https://blog.csdn.net/weixin_44267007/article/details/120365531)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值