java8优雅的代码风格

  1. List<TaskDetailResp.Remark> remarkList = oprHistoryList.stream()
  2. .filter(oprHis -> StringUtils.isNotBlank(oprHis.getRemark()))
  3. .map(oprHis -> {
  4. TaskDetailResp.Remark remark = new TaskDetailResp.Remark();
  5. remark.setOprName(oprHis.getOprName());
  6. remark.setOprTime(oprHis.getOprTime());
  7. remark.setRemark(oprHis.getRemark());
  8. retun remark;
  9. }).collect(Collectors.toList());
  10. StringInterger[] 1.http://www.it1352.com/531206.html
  11. Integer[] lineArray4 = Stream.of("1,2,3,4,5,6".split(",")).map(Integer::parseInt).toArray(Integer[]::new);
  12. Map->List
  13. List<Long> poiIdList = hotelInfoIndexVoList.stream().map(-> o.getPoiBaseId()).collect(Collectors.toList());
  14. List->Map
  15. Map<Long, Commodity> commodityMap = commodityList.stream().collect(Collectors.toMap(-> o.getCommodityId(), o -> o));
  16. Map<Integer,ProductDescRelation> relationMap = productDescRelationList.stream().collect(Collectors.toMap(obj->obj.getDescId(),obj->obj));
  17. orderDetailList.stream().forEach(-> {});
  18. 1.简单使用->http://www.jianshu.com/p/cbd5713a8f26
  19. Arrays.asList(1, 4, 2, 3, 5, 6, 7, 9, 0, 8)
  20. .stream()
  21. .sorted()// 排序
  22. .filter(-> x > 3)// 过滤
  23. .forEach(System.out::print);
  24. 运行结果:4,5,6,7,8,9
  25. list.stream().map(RadarContentResultVo::getContentId).collect(Collectors.toList()))
  26. 分组统计->1.https://segmentfault.com/a/1190000008184585
  27. 2.http://www.cnblogs.com/yangweiqiang/p/6934671.html
  28. 3.http://blog.csdn.net/lsmsrc/article/details/41120127
  29. 4.http://blog.csdn.net/lvshaorong/article/details/51810288
  30. 5.http://www.cnblogs.com/zxf330301/p/6586750.html
  31. Map<Long,List<PageAdsense>> adAdsenseMap = adAdsenseList.stream().filter(o->o.getStatus()==1 ).
  32. collect(Collectors.groupingBy(PageAdsense::getPageLayoutId,Collectors.toList()));
  33. 分组统计对象字段
  34. Map<Integer, List<Long>> pageLayoutMap = pageLayoutList.stream().sorted(comparing( PageLayout::getSort).reversed())
  35. .collect(Collectors.groupingBy( PageLayout::getComponentType,Collectors.mapping( PageLayout::getPageLayoutId, Collectors.toList())));
  36. 4. 求和
  37. 将集合中的数据按照某个属性求和:
  38. BigDecimal:
  39. //计算总金额
  40. BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
  41. System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
  42. Integer:
  43. //计算数量
  44. int sum = appleList.stream().mapToInt(Apple::getNum).sum();
  45. System.err.println("sum:"+sum); //sum:100
  46. 对象不同字段求和
  47. BigDecimal result =
  48. Stream.of(list.stream().map(OrderRefundInfo::getRefundPrice).reduce(BigDecimal.ZERO, BigDecimal::add),
  49. list.stream().map(OrderRefundInfo::getRefundIntegralPrice).reduce(BigDecimal.ZERO, BigDecimal::add))
  50. .reduce(BigDecimal.ZERO,BigDecimal::add);
  51. ListMap
  52. /**
  53. * List -> Map
  54. * 需要注意的是:
  55. * toMap 如果集合对象有重复的key,会报错Duplicate key ....
  56. * apple1,apple12的id都为1。
  57. * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
  58. */
  59. Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
  60. 打印appleMap
  61. {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}}
  62. targetStatisticsList.stream().collect(Collectors.toMap(TargetStatistics::getTargetId, TargetStatistics::getCollectCount));
  63.  
  64. 2. 分组
  65. List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
  66. //List 以ID分组 Map<Integer,List<Apple>>
  67. Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
  68.  
  69. System.err.println("groupBy:"+groupBy);
  70. {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}]}
  71. Map<Long, List<OrderFlightCharge>> flightChargeMap = flightCharges.stream().collect(Collectors.groupingBy(OrderFlightCharge::getOrderFlightDetailId));
  72. select city, count(*) from Employee group by city =>
  73. Map<String, Long> numEmployeesByCity = employees.stream().collect(groupingBy(Employee::getCity, counting()));
  74. {New York=1, Hong Kong=1, London=2}
  75. Map<String, List<Employee>> employeesByCity = employees.stream().collect(groupingBy(Employee::getCity));
  76. 添加排序http://blog.csdn.net/hatsune_miku_/article/details/73414406
  77. Set<Long> productIds = saleInfos.stream().collect(Collectors.groupingBy(CommodityHotelSaleInfo :: getProductId)).keySet();
  78. Map<Long,List<Commodity>> commodityMap = commoditys.stream().collect(Collectors.groupingBy(Commodity :: getCommodityId));
  79. map遍历
  80. map.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
  81. items.forEach((k,v)->{System.err.println("使用java8循环 /姓名 : " ++ " 分数 : " + v);});
  82. List<OrderFlightCharge> flightCharges=null; Map<Long, List<OrderFlightCharge>> flightChargeMap = null;
  83. lightChargeMap = flightCharges.stream().collect(Collectors.groupingBy(OrderFlightCharge::getOrderFlightDetailId));
  84. 给每个学生的名字后面加上个China:
  85. List<Student> mapResult = list.stream().map(-> {
  86. p.setName(p.getName() + " China");
  87. retun p;
  88. }).collect(Collectors.toList());
  89. mapResult.stream().forEach(-> {
  90. System.out.println(p.getName());
  91. });
  92. map函数的主要功能是对List中的每个元素进行处理并返回,可以返回其它的数据类型,例如:
  93. List<String> mapResult = list.stream().map(-> {
  94. p.setName(p.getName() + " China");
  95. retun p.getName();
  96. }).collect(Collectors.toList());
  97. mapResult.stream().forEach(-> {
  98. System.out.println(p);
  99. });
  100. 3. 过滤filter
  101. 从集合中过滤出来符合条件的元素
  102. //过滤出符合条件的数据
  103. List<Apple> filterList = appleList.stream().filter(-> a.getName().equals("香蕉")).collect(Collectors.toList());
  104. System.err.println("filterList:"+filterList);
  105. [Apple{id=2, name='香蕉', money=2.89, num=30}]
  106. filtermap结合起来用
  107. List<Student> result = list.stream().filter(-> StringUtils.equals("Jack", p.getName())).map(-> {
  108. p.setName(p.getName() + " China");
  109. retun p;
  110. }).collect(Collectors.toList());
  111. result.stream().forEach(-> {
  112. System.out.println(p.getName());
  113. });
  114. //stream and filter
  115. itemsList.stream().filter(itemuser->itemuser.getUserName().equals("xj")).forEach(item ->{
  116. System.out.println("...........stream........");
  117. System.err.println(item.getUserName());
  118. });
  119. 去重->http://www.cnblogs.com/CarpenterLee/p/6545321.html
  120. stream.distinct() .forEach(str -> System.out.println(str));
  121. 排序函数有两个,一个是用自然顺序排序,一个是使用自定义比较器排序,函数原型分别为
  122. stream.sorted((str1, str2) -> str1.length()-str2.length()).forEach(str -> System.out.println(str));
  123.  
  124. List排序
  125. 要对List中的对象进行排序以前非常麻烦,什么对象实现Comparable接口啊,写一个StudentComparator实现Comparator接口呀,非常麻烦,现在非常简单一行代码搞定(两种方式):
  126. list.sort(Comparator.comparing(Student::getName)); //按名字排序
  127. list.sort((p1,p2) -> {
  128. retun p1.getName().toLowerCase().compareTo(p2.getName().toLowerCase());
  129. });//lambda表达式
  130.  
  131. // 价格排序
  132. Collections.sort( roomRateList, new Comparator<HotelRoomRateVo>() {
  133. @Override
  134. public int compare(HotelRoomRateVo o1, HotelRoomRateVo o2) {
  135. retun o1.getAvgPrice().compareTo( o2.getAvgPrice() );
  136. }
  137.  
  138. } );
  139. mapToLong的使用demo
  140. double value = students.stream().filter(student -> "计算机科学".equals(student.getMajor())).mapToLong(aaa -> aaa.getId()).sum();
  141. flatMap
  142. 1.http://blog.csdn.net/u013803262/article/details/74370381
  143. String[] strs = {"java8", "is", "easy", "to", "use"};
  144. // 映射成为Stream<String[]>
  145. List<String[]> distinctStrs = Arrays.stream(strs).map(str -> str.split("")).distinct().collect(Collectors.toList());
  146.  
  147. studentss.stream().flatMap(students1 -> students1.stream()).max((o1, o2) -> (o1.getName().length() - o2.getName().length())).get().getName()
  148. flatmap可以在lamda中返回集合,然后flat为单个元素一个个放入最后的结果集中比如Person里头有个多个Hobby(List<Hobby>),那我想获取所有人的所有hobby,则可以:List<Person> persons = Set<Hobby> hobbySet = persons.parallelStream().flatMap(-> p.getHobbyList.stream())
  149. .collect(Collectors.toCollection(() -> new TreeSet<Hobby>((h1,h2) -> h1.getName().compareTo(h2.getName()))))
  150. map: 对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。这个方法有三个对于原始类型的变种方法,分别是:mapToIntmapToLongmapToDouble。这三个方法也比较好理解,比如mapToInt就是把原始Stream转换成一个新的Stream,这个新生成的Stream中的元素都是int类型。之所以会有这样三个变种方法,可以免除自动装箱/拆箱的额外消耗;
  151.  
  152. flatMap:和map类似,不同的是其每个元素转换得到的是Stream对象,会把子Stream中的元素压缩到父集合中;
  153. flatMap方法示意图:
  154.  
  155. Map<Long, List<Long>> categoryMap = null;
  156. List<Long> specialIdList = categoryMap.values().stream().flatMap( o -> o.stream() ).collect( Collectors.toList());
  157. 字符串操作
  158. List<Long> billboardIds=Arrays.stream(billboardList.get(0).getRecommendBillboardIds().split(",|,|;|;")).map( o ->SafeConvert.convertStringToLong( o, -1L ) ).filter( o -> -1L != o ).collect(Collectors.toList());
  159. 可以参考网址  https://www.pengyun.fun/cute-hand/public/api/showArticle?articleId=4
posted @ 2019-06-26 16:12  xiaoqingting2019  阅读(1535)  评论(0)    收藏  举报