Stream写法

1.stream处理方式

List<students> list = new ArrayList<students>();
list.add(new students("Anna",22,false));
list.add(new students("Anti",37,false));
list.add(new students("Annn",25,true));
list.add(new students("Annga",51,false));
List<students> newlist = new ArrayList<students>();
//lambda
list.forEach(ll->{
if (ll.getAge()>30) {
newlist.add(ll);
}
});
newlist.forEach(ll->System.out.println(ll));
//stream
List<students> list3 = list.stream().filter(l3->{return l3.getAge()>30;}).collect(Collectors.toList());
System.out.println(list3);
  • 1.需要把原列表转stream<javabean>

  • 2.调用stream过滤器方法filter

  • 3.使用lambda结合填写过滤条件

  • 4.调用collect收集过滤后的数据

  • 5.将收集好的数据转回list集合Collectors.toList()

2.只提取其中一列,map方式处理

List<students> list = new ArrayList<students>();
list.add(new students("aa", 12, true));
list.add(new students("bb", 16, true));
list.add(new students("cc", 20, true));
List<Integer> ageList = list.stream().map(l->l.getAge()).collect(Collectors.toList());
ageList.forEach(System.out::println);
List<Integer> ageList2 = list.stream().map(students::getAge).collect(Collectors.toList());
ageList.forEach(System.out::print);

3.按条件过滤

List<students> newList = list.stream().filter(l->l.getAge()>15).collect(Collectors.toList());
newList.forEach(System.out::println);
newList.forEach(l->System.out.print(l+"\t"));

4.调用某类的方法写法

students::getAge

5.某列数值-数值求和

//数值计算-求和
//一种方式是用Collectors的summingInt方法
int sum = list.stream().collect(Collectors.summingInt(students::getAge));
System.out.println(sum);
//mapToInt().sum()
int sum2 = list.stream().mapToInt(students::getAge).sum();
System.out.println(sum2);

6.取出集合符合条件的第一个元素

Optional<students> firstList = list.stream().filter(l->l.getAge()>15).findFirst();
if (firstList.isPresent()) {
System.out.println(firstList.get().getName());
}
//简写
list.stream().filter(l->l.getAge()>15).findFirst().ifPresent(ll->System.out.println(ll.getName()));

7. 对集合中对象字符列按规则拼接

System.out.println(list.stream().map(students::getName).collect(Collectors.joining("-")));
String ss = list.stream().map(students::getName).collect(Collectors.joining(","));
System.out.println("ss="+ss);

8.将集合元素提取,转为Map

Map<String, Object> map = list.stream().collect(Collectors.toMap(students::getName, students::getAge));
map.forEach((key,value)->System.out.println(key+"="+value));

9.按集合某一属性进行分组

Map<String, List<students>> mapGroup = list.stream().collect(Collectors.groupingBy(students::getName));
mapGroup.forEach((k,v)->System.out.println(k+"="+v.size()));

10.求集合对象数值列平均数

double ave1 = list.stream().collect(Collectors.averagingInt(students::getAge));
System.out.println(ave1);
double ave2 = list.stream().mapToDouble(students::getAge).average().getAsDouble();
System.out.println(ave2);

11.对集合按某一列排序

list.sort((x,y)->{
    if (x.getAge()>y.getAge()) {
        return 1;
    }else if (x.getAge()==y.getAge()) {
        return 0;
    }else {
        return -1;
    }
    });
list.forEach(l->System.out.println(l));