stream 使用记录
1、对集合List 中的某个BigDecimal 属性的就行汇总
使用map 进行映射后再通过reduce 进行规约
//得到需要合并的集合
List<Order> list = baseService.getAll(Order.class);
String s = list.stream().map(Order -> Order.getBhTaxTotal()).reduce(BigDecimal.ZERO, BigDecimal::add).toPlainString();
2、在需求开发中,我们需要对一个List中的对象进行唯一值属性去重,属性求和,对象假设为Pool,有name、value两个属性,其中name表示唯一值,需要value进行求和,并最后保持一份对象。
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Pool {
private String name;
private int value;
}
public static void main(String[] args) throws Exception {
List<Pool> list = new ArrayList<Pool>(){
{
add(new Pool("A", 1));
add(new Pool("A", 2));
add(new Pool("A", 3));
add(new Pool("B", 4));
add(new Pool("B", 5));
}
};
List<Pool> result = merge(list);
System.err.println(JSONObject.toJSONString(result));
}
/**
* @Description 使用Java8的流进行处理,将name相同的对象进行合并,将value属性求和
* @Title merge
* @Param [list]
* @Return java.util.List<Pool>
* @Author Louis
*/
public static List<Pool> merge(List<Pool> list) {
Map<String, Pool> map = new HashMap<String, Pool>();
list.stream().forEach(pool -> {
Pool last = map.get(pool.getName());
if(null != last){
pool.setValue(pool.getValue() + last.getValue());
}
map.put(pool.getName(), pool);
});
return map.values().stream().collect(Collectors.toList());
}
/**
* @Description 使用Java8的流进行处理,将name相同的对象进行合并,将value属性求和
* @Title merge
* @Param [list]
* @Return java.util.List<Pool>
* @Author Louis
*/
public static List<Pool> merge(List<Pool> list) {
List<Pool> result = list.stream()
// 表示name为key,接着如果有重复的,那么从Pool对象o1与o2中筛选出一个,这里选择o1,
// 并把name重复,需要将value与o1进行合并的o2, 赋值给o1,最后返回o1
.collect(Collectors.toMap(Pool::getName, a -> a, (o1,o2)-> {
o1.setValue(o1.getValue() + o2.getValue());
return o1;
})).values().stream().collect(Collectors.toList());
return result;
}
3、需求将一个集合【集合中包含有对象】进行重新构建新对象并分组,在分组过程中将分组后的数据按照对象的某个属性去重
JSONArray array = json.getJSONArray("data");
List<JSONObject> data = array.stream().map(a -> {
JSONObject obj = new JSONObject();
obj.put("emp_code",((JSONObject)a).getString("emp_code").replaceAll("^(0+)",""));
obj.put("emp_name",((JSONObject)a).getString("emp_name"));
obj.put("leader_code",((JSONObject)a).getString("leader_code"));
obj.put("leader_name",((JSONObject)a).getString("leader_name"));
obj.put("interface_time",((JSONObject)a).getString("interface_time"));
return obj;
}).collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item -> item.getString("emp_code")))
), ArrayList::new)
);
4、需求,集合中的数据存在重复的值,需要取出唯一值进行匹配
JSONObject leaderInfo = leaderInfoList.stream().filter(c ->
c.getString("emp_code").replaceAll("^(0+)","").equals(empProfile.getEmpNo())
).findFirst().orElse(null);
5、filter()的使用,filter过滤,其实就是一个判断条件,根据所写的添加筛选出新的流,可以结合stream 流中一些判断方法进行使用。
- anyMatch 有匹配则返回true
- allMatch 必须匹配所有才返回ture
- noneMatch 没有匹配则返回ture
//难些用法:查找两个list中的不同
public static void streamList(){
HashMap<String,String> hashMapOne = new HashMap<>();
hashMapOne.put("userid","one" );
HashMap<String,String> hashMapTwo = new HashMap<>();
hashMapTwo.put("userid","two" );
HashMap<String,String> hashMapThree = new HashMap<>();
hashMapThree.put("userid","three" );
List<HashMap<String,String>> listMap = new ArrayList<>();
listMap.add(hashMapOne);
listMap.add(hashMapTwo);
listMap.add(hashMapThree);
List<String> elementList = new ArrayList<>();
elementList.add("one");
elementList.add("three");
// Predicate<String> p = e->e.equals("one");
listMap.stream().map(map->map.get("userid"))
// .filter(p)
.filter(str->elementList.stream().noneMatch(e->e.equals(str)))
.collect(Collectors.toList())
.forEach(item->{
System.out.println(item);
});
}
结果:two
6、stream 进行求和
6.1 BigDecimal:
BigDecimal bb = list.stream.map(对象::getXXX).reduce(BigDeciaml.ZERO,BigDecimal::add);
6.2 Integer、Double、Long
list.stream.mapTo类型(对象::getXXX).sum();
7、stream 将list 中对象属性为null 移动至最前面或者最后面
- 使用sorted 方法
- Comparator.nullsFirst()、Comparator.nullsLast()
List<Stu> collect = list.stream().sorted(Comparator.comparing(Stu::getName, Comparator.nullsFirst(String::compareTo))).collect(Collectors.toList());
8、list 按照对象属性进行排序
- 使用sorted 方法
- 使用Comparator自带方法或者重写Comparator
List<EducationBackground> educationBackgroundList = resumeContent.getEducationBackground();
EducationBackground educationBackground = educationBackgroundList.stream().sorted(Comparator.comparing(EducationBackground::getStartDate, (o1, o2) -> {
boolean flag = DateUtils.compareTime(DateUtils.stringToDate(o2, "yyyy-MM-dd"), DateUtils.stringToDate(o1, "yyyy-MM-dd"));
if (flag) {
return -1;
}
return 1;
})).findFirst().orElse(null);
9、list 按照对象某个属性进行个数汇总
list.stream.collect(Collectors.groupingBy(类::getXXx,Collectors.counting));
10、list 元素为基本类型,对元素进行分组计算个数
- Function.identity()
List<String> list = new ArrayList();
Map<String,Long> collect = list.stream.collect(Collectors.groupingBy(Function.identity(),Collectors.couting()));