【規範程式碼】- JAVA 8
阿新 • • 發佈:2021-12-17
JAVA 8
契子:JAVA 8的stream流 是為了提高工作效率,使程式碼更加優雅、簡單
一、建立Stream
什麼是資料流? 集合講的是資料,而資料流講的是計算!
- 建立 Stream (一個數據源(如集合、陣列),獲取一個流)
- 中間操作(一箇中間操作,例如篩選、過濾等)
- 終止操作 (一個終止操作,最終產生結果)
List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 12, "male", "New York")); personList.add(new Person("Jack", 7000, 13,"male", "Washington")); personList.add(new Person("Lily", 7800, 24,"female", "Washington")); personList.add(new Person("Anni", 8200, 25,"female", "New York")); personList.add(new Person("Owen", 9500, 66,"male", "New York")); personList.add(new Person("Alisa", 7900, 52,"female", "New York")); stream<Person> str = personList.stream()
二、遍歷/匹配(foreach/find/match)
// foreach personList.stream().filter(x->x.getAge() > 40).forEach(System.out::print); // find (filter、findAny) Optional<Person> optional = personList.stream().filter(f -> f.getAge() == 12).findFirst() Optional<Person> optional = personList.parallelStream().findAny(); // match (返回 true、false) 是否包含 personList.stream().anyMatch(x -> x.getAge() > 52)
三、filter(過濾)、map(對映)
// 過濾 personList.stream().filter(x->x.getSalary() ==8900).collect(Collectors.toList()) // Map (取其中一列) personList.stream().map(x->x.getSalary()).collect(Collectors.toList()) // 過濾 + Map personList.stream().filter(f->f.getSalary()==7900).map(x->x.getSalary()).collect(Collectors.toList()) // 對映 案例 (工資整體加1W) personList.stream().map(person -> { person.setSalary(person.getSalary() + 10000); return person; }).collect(Collectors.toList());
四、 聚合(max/min/平均值)
// min
personList.stream().min(Comparator.comparingInt(Person::getAge))
// max
personList.stream().max(Comparator.comparingInt(Person::getAge))
// BigDecimal 求最大值
personList.stream().map(x-x.getSalaryByBigDecimal()).max(BigDecimal::compareTo);
// BigDecimal 求最小值
personList.stream().map(x->x.getSalaryByBigDecimal()).min(BigDecimal::compareTo)
五、歸約(reduce)
主要是針對BigDecimal
// BigDecimal 求和
personList.stream().map(x->x.getSalaryByBigDecimal()).reduce(BigDecimal::add)
// BigDecimal 乘法
personList.stream().map(x->x.getSalaryByBigDecimal()).reduce(BigDecimal::multiply)
// BigDecimal 平均值
BigDecimal average = userList.stream().map(vo -> ObjectUtils.isEmpty(vo.getWeight()) ? new BigDecimal(0) : vo.getWeight()).reduce(BigDecimal.ZERO, BigDecimal::add).divide(BigDecimal.valueOf(userList.size()), 2, BigDecimal.ROUND_HALF_UP);
六、收集( collect )
collect
,收集,可以說是內容最繁多、功能最豐富的部分了。從字面上去理解,就是把一個流收集起來,最終可以是收整合一個值也可以收整合一個新的集合。
// toList
personList.stream().filter(x>x.getAge()==12).collect(Collectors.toList())
// toSet
personList.stream().map(x->x.getSex()).collect(Collectors.toSet())
// toMap
Map<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, p -> p))
七、統計(count/averaging)
Collectors 工具類 針對Double ,Integer
// 求總數
Long count = personList.stream().collect(Collectors.counting());
// 求平均工資
Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary));
// 求最高工資
Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare));
// 求工資之和
Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary));
// 一次性統計所有資訊
DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary));
八、分組(partitioningBy/groupingBy)
partitioningBy: 返回值是Map的key是boolean型別,也就是這個函式的返回值只能將資料分為兩組也就是ture和false兩組資料
groupingBy: 但是他的key是泛型,那麼這個分組就會將資料分組成多個key的形式
// 將員工按薪資是否高於8000分組
Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000));
// 將員工按性別分組
Map<String, List<Person>> group = personList.stream().collect(Collectors.groupingBy(Person::getSex));
// 多次分組 先按員工性別分組再按員工地區分組
personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
九、接合(joining)
joining
可以將stream中的元素用特定的連線符(沒有的話,則直接連線)連線成一個字串。
personList.stream().map(p -> p.getName()).collect(Collectors.joining(","))
十、 排序(sorted)
sorted,中間操作。有兩種排序:
- sorted():自然排序,流中元素需實現Comparable介面
- sorted(Comparator com):Comparator排序器自定義排序
// 按工資升序排序(自然排序)
List<String> newList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName)
.collect(Collectors.toList());
// 按工資倒序排序
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName).collect(Collectors.toList());
// 先按工資再按年齡升序排序
List<String> newList3 = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
.collect(Collectors.toList());
Collections.reverse
Collections.sort
十一、 合併、去重、限制、跳過
// 合併 去重
String[] arr1 = { "a", "b", "c", "d" };
String[] arr2 = { "d", "e", "f", "g" };
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
// concat:合併兩個流 distinct:去重
List<String> newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
// 限制
List<Person> collect = personList.stream().limit(4).collect(Collectors.toList());
// 跳過
long pageNo = 3;
long pageSize =2;
List<Person> collect = personList.stream().skip((pageNo-1)*pageSize).limit(2).collect(Collectors.toList());
collect.stream().forEach(System.out::println);