java8优雅的代码风格
- List<TaskDetailResp.Remark> remarkList = oprHistoryList.stream()
- .filter(oprHis -> StringUtils.isNotBlank(oprHis.getRemark()))
- .map(oprHis -> {
- TaskDetailResp.Remark remark = new TaskDetailResp.Remark();
- remark.setOprName(oprHis.getOprName());
- remark.setOprTime(oprHis.getOprTime());
- remark.setRemark(oprHis.getRemark());
- retun remark;
- }).collect(Collectors.toList());
- String转Interger[] 1.http://www.it1352.com/531206.html
- Integer[] lineArray4 = Stream.of("1,2,3,4,5,6".split(",")).map(Integer::parseInt).toArray(Integer[]::new);
- Map->List
- List<Long> poiIdList = hotelInfoIndexVoList.stream().map(o -> o.getPoiBaseId()).collect(Collectors.toList());
- List->Map
- Map<Long, Commodity> commodityMap = commodityList.stream().collect(Collectors.toMap(o -> o.getCommodityId(), o -> o));
- Map<Integer,ProductDescRelation> relationMap = productDescRelationList.stream().collect(Collectors.toMap(obj->obj.getDescId(),obj->obj));
- orderDetailList.stream().forEach(o -> {});
- 1.简单使用->http://www.jianshu.com/p/cbd5713a8f26
- Arrays.asList(1, 4, 2, 3, 5, 6, 7, 9, 0, 8)
- .stream()
- .sorted()// 排序
- .filter(x -> x > 3)// 过滤
- .forEach(System.out::print);
- 运行结果:4,5,6,7,8,9
- list.stream().map(RadarContentResultVo::getContentId).collect(Collectors.toList()))
- 分组统计->1.https://segmentfault.com/a/1190000008184585
- 2.http://www.cnblogs.com/yangweiqiang/p/6934671.html
- 3.http://blog.csdn.net/lsmsrc/article/details/41120127
- 4.http://blog.csdn.net/lvshaorong/article/details/51810288
- 5.http://www.cnblogs.com/zxf330301/p/6586750.html
- Map<Long,List<PageAdsense>> adAdsenseMap = adAdsenseList.stream().filter(o->o.getStatus()==1 ).
- collect(Collectors.groupingBy(PageAdsense::getPageLayoutId,Collectors.toList()));
- 分组统计对象字段
- Map<Integer, List<Long>> pageLayoutMap = pageLayoutList.stream().sorted(comparing( PageLayout::getSort).reversed())
- .collect(Collectors.groupingBy( PageLayout::getComponentType,Collectors.mapping( PageLayout::getPageLayoutId, Collectors.toList())));
- 4. 求和
- 将集合中的数据按照某个属性求和:
- BigDecimal:
- //计算总金额
- BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
- System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
- Integer:
- //计算数量
- int sum = appleList.stream().mapToInt(Apple::getNum).sum();
- System.err.println("sum:"+sum); //sum:100
- 对象不同字段求和
- BigDecimal result =
- Stream.of(list.stream().map(OrderRefundInfo::getRefundPrice).reduce(BigDecimal.ZERO, BigDecimal::add),
- list.stream().map(OrderRefundInfo::getRefundIntegralPrice).reduce(BigDecimal.ZERO, BigDecimal::add))
- .reduce(BigDecimal.ZERO,BigDecimal::add);
- List转Map
- /**
- * List -> Map
- * 需要注意的是:
- * toMap 如果集合对象有重复的key,会报错Duplicate key ....
- * apple1,apple12的id都为1。
- * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
- */
- Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
- 打印appleMap:
- {1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='香蕉', money=2.89, num=30}, 3=Apple{id=3, name='荔枝', money=9.99, num=40}}
- targetStatisticsList.stream().collect(Collectors.toMap(TargetStatistics::getTargetId, TargetStatistics::getCollectCount));
- 2. 分组
- List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
- //List 以ID分组 Map<Integer,List<Apple>>
- Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
- System.err.println("groupBy:"+groupBy);
- {1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}
- Map<Long, List<OrderFlightCharge>> flightChargeMap = flightCharges.stream().collect(Collectors.groupingBy(OrderFlightCharge::getOrderFlightDetailId));
- select city, count(*) from Employee group by city =>
- Map<String, Long> numEmployeesByCity = employees.stream().collect(groupingBy(Employee::getCity, counting()));
- {New York=1, Hong Kong=1, London=2}
- Map<String, List<Employee>> employeesByCity = employees.stream().collect(groupingBy(Employee::getCity));
- 添加排序http://blog.csdn.net/hatsune_miku_/article/details/73414406
- Set<Long> productIds = saleInfos.stream().collect(Collectors.groupingBy(CommodityHotelSaleInfo :: getProductId)).keySet();
- Map<Long,List<Commodity>> commodityMap = commoditys.stream().collect(Collectors.groupingBy(Commodity :: getCommodityId));
- map遍历
- map.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
- items.forEach((k,v)->{System.err.println("使用java8循环 /姓名 : " +k + " 分数 : " + v);});
- List<OrderFlightCharge> flightCharges=null; Map<Long, List<OrderFlightCharge>> flightChargeMap = null;
- lightChargeMap = flightCharges.stream().collect(Collectors.groupingBy(OrderFlightCharge::getOrderFlightDetailId));
- 给每个学生的名字后面加上个China:
- List<Student> mapResult = list.stream().map(p -> {
- p.setName(p.getName() + " China");
- retun p;
- }).collect(Collectors.toList());
- mapResult.stream().forEach(p -> {
- System.out.println(p.getName());
- });
- map函数的主要功能是对List中的每个元素进行处理并返回,可以返回其它的数据类型,例如:
- List<String> mapResult = list.stream().map(p -> {
- p.setName(p.getName() + " China");
- retun p.getName();
- }).collect(Collectors.toList());
- mapResult.stream().forEach(p -> {
- System.out.println(p);
- });
- 3. 过滤filter
- 从集合中过滤出来符合条件的元素
- //过滤出符合条件的数据
- List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
- System.err.println("filterList:"+filterList);
- [Apple{id=2, name='香蕉', money=2.89, num=30}]
- filter和map结合起来用
- List<Student> result = list.stream().filter(p -> StringUtils.equals("Jack", p.getName())).map(p -> {
- p.setName(p.getName() + " China");
- retun p;
- }).collect(Collectors.toList());
- result.stream().forEach(p -> {
- System.out.println(p.getName());
- });
- //stream and filter
- itemsList.stream().filter(itemuser->itemuser.getUserName().equals("xj")).forEach(item ->{
- System.out.println("...........stream........");
- System.err.println(item.getUserName());
- });
- 去重->http://www.cnblogs.com/CarpenterLee/p/6545321.html
- stream.distinct() .forEach(str -> System.out.println(str));
- 排序函数有两个,一个是用自然顺序排序,一个是使用自定义比较器排序,函数原型分别为
- stream.sorted((str1, str2) -> str1.length()-str2.length()).forEach(str -> System.out.println(str));
- List排序
- 要对List中的对象进行排序以前非常麻烦,什么对象实现Comparable接口啊,写一个StudentComparator实现Comparator接口呀,非常麻烦,现在非常简单一行代码搞定(两种方式):
- list.sort(Comparator.comparing(Student::getName)); //按名字排序
- list.sort((p1,p2) -> {
- retun p1.getName().toLowerCase().compareTo(p2.getName().toLowerCase());
- });//lambda表达式
- // 价格排序
- Collections.sort( roomRateList, new Comparator<HotelRoomRateVo>() {
- @Override
- public int compare(HotelRoomRateVo o1, HotelRoomRateVo o2) {
- retun o1.getAvgPrice().compareTo( o2.getAvgPrice() );
- }
- } );
- mapToLong的使用demo
- double value = students.stream().filter(student -> "计算机科学".equals(student.getMajor())).mapToLong(aaa -> aaa.getId()).sum();
- flatMap
- 1.http://blog.csdn.net/u013803262/article/details/74370381
- String[] strs = {"java8", "is", "easy", "to", "use"};
- // 映射成为Stream<String[]>
- List<String[]> distinctStrs = Arrays.stream(strs).map(str -> str.split("")).distinct().collect(Collectors.toList());
- studentss.stream().flatMap(students1 -> students1.stream()).max((o1, o2) -> (o1.getName().length() - o2.getName().length())).get().getName()
- flatmap可以在lamda中返回集合,然后flat为单个元素一个个放入最后的结果集中比如Person里头有个多个Hobby(List<Hobby>),那我想获取所有人的所有hobby,则可以:List<Person> persons = Set<Hobby> hobbySet = persons.parallelStream().flatMap(p -> p.getHobbyList.stream())
- .collect(Collectors.toCollection(() -> new TreeSet<Hobby>((h1,h2) -> h1.getName().compareTo(h2.getName()))))
- map: 对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。这个方法有三个对于原始类型的变种方法,分别是:mapToInt,mapToLong和mapToDouble。这三个方法也比较好理解,比如mapToInt就是把原始Stream转换成一个新的Stream,这个新生成的Stream中的元素都是int类型。之所以会有这样三个变种方法,可以免除自动装箱/拆箱的额外消耗;
- flatMap:和map类似,不同的是其每个元素转换得到的是Stream对象,会把子Stream中的元素压缩到父集合中;
- flatMap方法示意图:
- Map<Long, List<Long>> categoryMap = null;
- List<Long> specialIdList = categoryMap.values().stream().flatMap( o -> o.stream() ).collect( Collectors.toList());
- 字符串操作
- List<Long> billboardIds=Arrays.stream(billboardList.get(0).getRecommendBillboardIds().split(",|,|;|;")).map( o ->SafeConvert.convertStringToLong( o, -1L ) ).filter( o -> -1L != o ).collect(Collectors.toList());
- 可以参考网址 https://www.pengyun.fun/cute-hand/public/api/showArticle?articleId=4
锦绣文章,滔滔不绝;大好前程,鹏程万里!
浙公网安备 33010602011771号