java8日常使用笔记
2022-01-21 本文已影响0人
wang_cheng
public class Test {
public static class Student {
public Student(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
private Integer id;
private String name;
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
public static void main(String[] args) {
//(1)中间操作:filter(Predicate<T>), map(Function(T, R), limit, sorted(Comparator<T>), distinct,flatMap;
//(2)终端操作:只有终端操作才能产生输出,包括:allMatch, anyMatch, noneMatch, findAny, findFirst, forEach, collect, reduce, count
List<Integer> list = Arrays.asList(1,2,3,4,5,6,6,6);
List<Student> studentList = Arrays.asList(new Student(1,"cheng1",21),
new Student(2,"cheng2",22),
new Student(3,"cheng3",23));
//过滤filter
List<Integer> collect = list.stream().filter(var -> var != 3).collect(Collectors.toList());
System.out.println("过滤3的集合为:"+collect);
//去重distinct
List<Integer> distinctList = list.stream().distinct().collect(Collectors.toList());
System.out.println("去重复list:"+distinctList);
//跳过前n个 skip
List<Integer> skipList = list.stream().skip(3).collect(Collectors.toList());
System.out.println("skipList = " + skipList);
//匹配
boolean anyMatch = list.stream().anyMatch(var -> var == 2);
System.out.println("anyMatch = " + anyMatch);
//获取第一个 findFirst
Integer firstV = list.stream().findFirst().orElse(999);
System.out.println("firstV = " + firstV);
//使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行的情况,那就不能确保是第一个
Integer anyV = list.stream().findAny().get();
System.out.println("anyV = " + anyV);
System.out.println("串行findAny"+IntStream.range(0, 100).findAny());
System.out.println("并行findAny"+IntStream.range(0, 100).parallel().findAny());
//排序
list.sort(Comparator.reverseOrder());
System.out.println("倒序"+list);
//对象排序
studentList.sort(Comparator.comparing(Student::getAge).reversed().thenComparing(Student::getId));
System.out.println("根据年龄排序:"+studentList);
//Collectors.toMap 转换为Map格式 {k=id,v=student}
Map<Integer, Student> studentIdMap = studentList.stream().collect(Collectors.toMap(Student::getId, Function.identity(), (k1, k2) -> k1));
//分组 Collectors.groupingBy 年龄分组 k=年龄 v=list(student)
Map<Integer, List<Student>> ageGroupList = studentList.stream().collect(Collectors.groupingBy(Student::getAge));
//自定义分组 以名字+年龄分组 k= 名字+年龄 v=list(student)
Map<String, List<Student>> nameAndAgeGroupList = studentList.stream().collect(Collectors.groupingBy(var -> var.getName() + "" + var.getAge()));
//分组后在 组装value内容 Collectors.mapping 对结果进行映射操作
Map<Integer, List<Student>> mappingMap = studentList.stream()
.collect(Collectors.groupingBy(Student::getAge, Collectors.mapping(var -> new Student(var.getAge(), var.getName()+"我是组装", var.getAge()+1), Collectors.toList())));
//map
List<Integer> studentIds = studentList.stream().map(Student::getId).collect(Collectors.toList());
//求值
//reduce归约,将流中的值结合起来,得到一个值
//求和
Integer sum = list.stream().reduce(Integer::sum).get();
System.out.println("sum = " + sum);
Integer sum3 = list.stream().collect(Collectors.summingInt(var -> var));
//年龄累加
Integer ageSum = studentList.stream().collect(Collectors.reducing(0, Student::getAge, (a, b) -> a + b));
System.out.println("ageSum = " + ageSum);
//最大值
Integer max = list.stream().max(Comparator.comparing(Function.identity())).get();
System.out.println("max = " + max);
//收集数据统计
IntSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingInt(var -> var));
//平均数
double average = summaryStatistics.getAverage();
System.out.println("average = " + average);
//求和
long sum1 = summaryStatistics.getSum();
System.out.println("sum1 = " + sum1);
//最大
int max1 = summaryStatistics.getMax();
System.out.println("max1 = " + max1);
//最小
int min = summaryStatistics.getMin();
System.out.println("min = " + min);
long count = summaryStatistics.getCount();
System.out.println("count = " + count);
//字符串join
String joinStr = Stream.of("a", "b", "c").collect(Collectors.joining(",","[","]"));
System.out.println("joinStr = " + joinStr);
Map map = new HashMap();
map.put("a",1);
map.put("b",2);
map.put("c",3);
StringJoiner joiner = new StringJoiner("&");
map.forEach((k,v)->{
String var = k+"="+v;
joiner.add(var);
});
System.out.println("joiner = " + joiner.toString());
//随机数生成
List<Integer> randomInt = Stream.generate(() -> {
Random random = new Random();
return random.nextInt(10);
}).limit(10).collect(Collectors.toList());
System.out.println("randomInt = " + randomInt);
//函数接口使用
Supplier<String> supplier = ()->"hahahah,我无入参";
System.out.println(supplier.get());//hahahah,我无入参
//接受入参 无返回值
Consumer<String> consumer = var-> System.out.println(var);
consumer.accept("hello");//hello
//接受类型参数,返回boolean
Predicate<String> predicate = var-> StringUtils.isBlank(var);
System.out.println(predicate.test(""));//true
//接受1个参数,返回一个参数
Function<String,Integer> function = var-> {
if (var.equals("a")) {
return 1;
}
return 0;
};
System.out.println(function.apply("a"));
}
}