FWQ
两种 Collect 操作获取最大 id 菜单项的区别是什么?
两种 collect 操作写法的 对于给定的 menulist,我们想要获取其中 id最大的菜单项。下面提供了两种使用 collectors 进行此操作的写法: 第一种写法: menulist.stream().collect(collectors.maxby(comparator.comparing(menu::getid))).get(); 登录后复制 第二种写法: menulist.stream().collect(collectors.collectingandthen(collectors.maxby(comparator.comparing(menu::getid)), optional::get)); 登录后复制 区别: 这两种写法在功能上等同,都能获得 id最大的菜单项。但是,它们在实现细节上有以下区别: 流处理流程: 第一写法使用 collectors.maxby 对流进行排序并获取最大值,然后使用 .get() 方法解包 optional。 第二写法先使用 collectors.maxby 找到最大值,然后使用…