一起来学Java8(七)——Stream(中)
在 一起来学Java8(七)——Stream(上) 中我们了解到了Stream对象的常用方法以及用法。现在一起来深入了解下 Stream.collect() 方法的使用 collect基本用法 collect意思为收集,它是对Stream中的元素进行收集和归纳,返回一个新的集合对象。先来看一个简单例子: public class CollectTest { @Data @AllArgsConstructor static class Goods { private String goodsName; private int price; } public static void main(String[] args) { List<Goods> list = Arrays.asList( new Goods("iphoneX", 4000) , new Goods("mate30 pro", 5999) , new Goods("redmek20", 2999) ); List<String> nameList = list.stream() .map(Goods::getGoodsName) .collect(Collectors.toList()); } } 在这个例子中,通过map方法返回商品名称,然后把所有的商品名称放到了List对象中。 查看源码发现