List 类的Stream处理:
List<String> list = new ArrayList<String>();
list.add("djk");
list.add("djk1");
list.add("djk12");
// map
list = list.stream().map(item->item.toUpperCase()).collect(Collectors.toList());
// filter
list = list.stream().filter(item->!item.equals("djk")).collect(Collectors.toList());
//flatMap
List<String> list = new ArrayList<>();
list.add("aaa bbb ccc");
list.add("ddd eee fff");
list.add("ggg hhh iii");
list = list.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).collect(toList());
class Apple {
private Integer id;
private String name;
private BigDecimal money;
private Integer num;
public Apple(Integer id, String name, BigDecimal money, Integer num) {
this.id = id;
this.name = name;
this.money = money;
this.num = num;
}
}
List<Apple> appleList = new ArrayList<>();//存放apple对象集合
Apple apple1 = new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 = new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 = new Apple(3,"荔枝",new BigDecimal("9.99"),40);
// group by用法
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
// 根据id去重
List<Person> unique = appleList.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
);
// List转Map
// (k1,k2)->k1 表示当k1,k2 2个key冲突的时候,选择k1
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
List<Student> list = Lists.newArrayList();
list.add(new Student("测试", "男", 18));
//按性别进行分组统计人数
Map<String, Integer> map = list.stream().collect(Collectors.groupingBy(Student::getSex, Collectors.summingInt(p -> 1)));
//判断是否有年龄大于25岁的学生
boolean check = list.stream().anyMatch(student -> student.getAge() > 25);
//按照年龄从小到大排序
List<Student> l3 = list.stream().sorted((s1, s2) -> s1.getAge().compareTo(s2.getAge())).collect(toList());
//求年龄最小的两个学生
List<Student> l4 = list.stream().limit(2).collect(toList());
list.removeif(e -> e.getAge()==25);
list.sort((o1, o2) -> o1.getAge() - o2.getAge());
java8 Map的新方法
// map merge()
class Students{
String name;
String subject
int score;
}
Map<String, Integer> studentScoreMap2 = new HashMap<>();
studentScoreList.forEach(studentScore -> studentScoreMap2.merge(
studentScore.getStuName(),
studentScore.getScore(),
Integer::sum));
System.out.println(objectMapper.writeValueAsString(studentScoreMap2));
// 结果如下:
// {"李四":228,"张三":215,"王五":235}
// key = 10 對應的value不存在, 則用101010 覆蓋
Map<Integer, String> map = new HashMap();
String s1 = map.putIfAbsent(10, "101010");