方法引用
[3]对象方法引用: 类名::实例方法. (参数1,参数2)->参数1.实例方法(参数2)
public class Test03 {
public static void main(String[] args) {
//[3]对象方法引用: 类名::实例方法. (参数1,参数2)->参数1.实例方法(参数2)
// Function<String,Integer> function=(str)->{
// return str.length();
// };
// Function<String,Integer> function=String::length;
//
// Integer len = function.apply("hello");
// System.out.println(len);
//比较两个字符串的内容是否一致.T, U, R
// R apply(T t, U u);
// BiFunction<String,String,Boolean> bi=(t,u)->{
// return t.equals(u);
// };
// BiFunction<String,String,Boolean> bi=String::equals;
// Boolean aBoolean = bi.apply("hello", "world");
// System.out.println(aBoolean);
// [4]构造方法引用: 类名::new (参数)->new 类名(参数)
// Supplier<String> supplier=()->{
// return new String("hello");
// };
// Supplier<People> supplier=People::new;
// Function<String,People> function=(n)->new People(n);
Function<String,People> function= People::new;
People s = function.apply("张三");
System.out.println(s);
}
}
class People{
private String name;
public People() {
}
public People(String name) {
this.name = name;
}
@Override
public String toString() {
return "People{" +
"name='" + name + '\'' +
'}';
}
}
Stream流
Java8的两个重大改变,一个是Lambda表达式,另一个就是本节要讲的Stream API表达式。==Stream 是Java8中处理集合的关键抽象概念==,它可以对集合进行非常复杂的查找、过滤、筛选等操作.
4.1 为什么使用Stream流
当我们需要对集合中的元素进行操作的时候,除了必需的添加、删除、获取外,最典型的就是集合遍历。我们来体验 集合操作数据的弊端,需求如下:
一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰,何线程 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
代码如下:
public class My {
public static void main(String[] args) {
// 一个ArrayList集合中存储有以下数据:张无忌,周芷若,赵敏,张强,张三丰
// 需求:1.拿到所有姓张的 2.拿到名字长度为3个字的 3.打印这些数据
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰");
// 1.拿到所有姓张的
ArrayList<String> zhangList = new ArrayList<>(); // {"张无忌", "张强", "张三丰"}
for (String name : list) {
if (name.startsWith("张")) {
zhangList.add(name);
}
}
// 2.拿到名字长度为3个字的
ArrayList<String> threeList = new ArrayList<>(); // {"张无忌", "张三丰"}
for (String name : zhangList) {
if (name.length() == 3) {
threeList.add(name);
}
}
// 3.打印这些数据
for (String name : threeList) {
System.out.println(name);
}
}
}
分析:
这段代码中含有三个循环,每一个作用不同:
首先筛选所有姓张的人;
然后筛选名字有三个字的人;
最后进行对结果进行打印输出。
每当我们需要对集合中的元素进行操作的时候,总是需要进行循环、循环、再循环。这是理所当然的么?不是。循环 是做事情的方式,而不是目的。每个需求都要循环一次,还要搞一个新集合来装数据,如果希望再次遍历,只能再使 用另一个循环从头开始。
那Stream能给我们带来怎样更加优雅的写法呢?
Stream的更优写法
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "张无忌", "周芷若", "赵敏", "张强", "张三丰","何线程");
list.stream()
.filter(item->item.startsWith("张"))
.filter(item->item.length()==3)
.forEach(item-> System.out.println(item));
}
}
对集合的操作语法简洁:性能比传统快。
4.2 Stream流的原理
注意:Stream和IO流(InputStream/OutputStream)没有任何关系,请暂时忘记对传统IO流的固有印象!
Stream流式思想类似于工厂车间的“生产流水线”,Stream流不是一种==数据结构==,==不保存数据==,而是对数据进行==加工 处理==。Stream可以看作是流水线上的一个工序。在流水线上,通过多个工序让一个原材料加工成一个商品。
Stream不存在数据,只对数据进行加工处理。
如何获取Stream流对象。
public class Test02 {
public static void main(String[] args) {
//通过集合对象调用stream()获取流
List<String> list=new ArrayList<>();
list.add("三个字");
list.add("千年");
list.add("王八");
list.add("乌龟");
Stream<String> stream = list.stream();
//通过Arrays数组工具类获取Stream对象
int[] arr={3,4,5,63,2,34};
IntStream stream1 = Arrays.stream(arr);
//使用Stream类中of方法
Stream<String> stream2 = Stream.of("hello", "world", "spring", "java");
//LongStream
LongStream range = LongStream.range(1, 10);
//上面都是获取的串行流。还可以获取并行流。如果流中的数据量足够大,并行流可以加快处速度。
Stream<String> stringStream = list.parallelStream();
//
// stringStream.forEach(item-> System.out.println(item));
stringStream.forEach(System.out::println);
}
}
Stream流中常见的api
中间操作api: 一个操作的中间链,对数据源的数据进行操作。而这种操作的返回类型还是一个Stream对象。
终止操作api: 一个终止操作,执行中间操作链,并产生结果,返回类型不在是Stream流对象。
(1)filter / foreach / count
static List<Person> personList = new ArrayList<Person>();
private static void initPerson() {
personList.add(new Person("张三", 8, 3000));
personList.add(new Person("李四", 18, 5000));
personList.add(new Person("王五", 28, 7000));
personList.add(new Person("孙六", 38, 9000));
}
class Person {
private String name;
private Integer age;
private String country;
private char sex;
public Person(String name, Integer age, String country, char sex) {
this.name = name;
this.age = age;
this.country = country;
this.sex = sex;
}
}
List<Person> personList = new ArrayList<>();
personList.add(new Person("欧阳雪",18,"中国",'F'));
personList.add(new Person("Tom",24,"美国",'M'));
personList.add(new Person("Harley",22,"英国",'F'));
personList.add(new Person("向天笑",20,"中国",'M'));
personList.add(new Person("李康",22,"中国",'M'));
personList.add(new Person("小梅",20,"中国",'F'));
personList.add(new Person("何雪",21,"中国",'F'));
personList.add(new Person("李康",22,"中国",'M'));
(2) map | sorted
map--接收Lambda,将元素转换成其他形式或提取信息。接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
//对流中元素排序
personList.stream()
.sorted((o1,o2)->o1.getAge()-o2.getAge())
.forEach(System.out::println);
//集合中每个元素只要名.map--->原来流中每个元素转换为另一种格式。
// personList.stream()
// .map(item->{
// Map<String,Object> m=new HashMap<>();
// m.put("name",item.getName());
// m.put("age",item.getAge());
// return m;
// })
// .forEach(System.out::println);
min max
(3)
获取员工中年龄最大的人
//查找最大年龄的人. max终止操作 Optional<Person> max = personList.stream().max((o1, o2) -> o1.getAge() - o2.getAge()); System.out.println(max.get());
(4)规约reduce
//求集合中所有人的年龄和。
Optional<Integer> reduce = personList.stream()
.map(item -> item.getAge())
.reduce((a, b) -> a + b);
System.out.println(reduce.get());
Integer reduce = personList.stream()
.map(item -> item.getAge())
.reduce(10, (a, b) -> a + b);
System.out.println(reduce);
(5)collect搜集 match find
//findFirst match
// Optional<Person> first = personList.parallelStream().filter(item -> item.getSex() == 'F').findAny();
boolean b = personList.parallelStream().filter(item -> item.getSex() == 'F').noneMatch(item -> item.getAge() >= 20);
System.out.println(b);
//搜集方法 collect 它属于终止方法
//年龄大于20且性别为M
// List<Person> collect = personList.stream()
// .filter(item -> item.getAge() > 20)
// .filter(item -> item.getSex() == 'M')
// .collect(Collectors.toList());
//
// System.out.println(collect);
新增了日期时间类
旧的日期时间的缺点:
设计比较乱: Date日期在java.util和java.sql也有,而且它的时间格式转换类在java.text包。
线程不安全。
新增加了哪些类?
LocalDate: 表示日期类。yyyy-MM-dd
LocalTime: 表示时间类。 HH:mm:ss
LocalDateTime: 表示日期时间类 yyyy-MM-dd t HH:mm:ss sss
DatetimeFormatter:日期时间格式转换类。
Instant: 时间戳类。
Duration: 用于计算两个日期类
public class Test {
public static void main(String[] args) {
LocalDate now = LocalDate.now(); //获取当前日期
LocalDate date = LocalDate.of(2022, 8, 23);//指定日期
LocalTime now1 = LocalTime.now();//当前时间
LocalTime of = LocalTime.of(17, 30, 20, 600);
LocalDateTime now2 = LocalDateTime.now();//获取当前日期时间
LocalDateTime now3 = LocalDateTime.of(2022,6,20,17,45,20);
Duration between = Duration.between(now2, now3);
System.out.println(between.toHours());
DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate parse = LocalDate.parse("1999-12-12", dateTimeFormatter);//把字符串转换为日期格式
String format = parse.format(dateTimeFormatter);
}
}
交易员类
public class Trader {
private final String name;
private final String city;
public Trader(String name, String city) {
this.name = name;
this.city = city;
}
public String getName() {
return name;
}
public String getCity() {
return city;
}
@Override
public String toString() {
return "Trader{" +
"name='" + name + '\'' +
", city='" + city + '\'' +
'}';
}
}
Transaction(交易记录)
public class Transaction {
private final Trader trader;
private final int year;
private final int value;
public Transaction(Trader trader, int year, int value){
this.trader = trader;
this.year = year;
this.value = value;
}
public Trader getTrader(){
return this.trader;
}
public int getYear(){
return this.year;
}
public int getValue(){
return this.value;
}
public String toString(){
return "{" + this.trader + ", " +
"year: "+this.year+", " +
"value:" + this.value +"}";
}
}
Trader raoul = new Trader("Raoul", "Cambridge");
Trader mario = new Trader("Mario", "Milan");
Trader alan = new Trader("Alan", "Cambridge");
Trader brian = new Trader("Brian", "Cambridge");
List<Transaction> transactions = Arrays.asList(
new Transaction(brian, 2011, 300),
new Transaction(raoul, 2012, 1000),
new Transaction(raoul, 2011, 400),
new Transaction(mario, 2012, 710),
new Transaction(mario, 2012, 700),
new Transaction(alan, 2012, 950)
);
(1) 找出2011年发生的所有交易,并按交易额排序(从低到高)。
(2) 交易员都在哪些不同的城市工作过?
(3) 查找所有来自于剑桥的交易员,并按姓名排序。
(4) 返回所有交易员的姓名字符串,按字母顺序排序。
(5) 有没有交易员是在米兰工作的?
(6) 打印生活在剑桥的交易员的所有交易额。
(7) 所有交易中,最高的交易额是多少?
(8) 找到交易额最小的交易。
//(1)
// transactions.stream().filter(item -> item.getYear() == 2011)
// .sorted((o1, o2) -> o2.getValue()- o1.getValue())
// .forEach(System.out::println);
//(2)
//transactions.stream().map(item->item.getTrader()).map(item->item.getCity())
// .distinct()
// .forEach(System.out::println);
//(3)
transactions.stream().filter(item->item.getTrader().getCity()=="Cambridge")
.map(item->item.getTrader())
.sorted(Comparator.comparing((item)->item.getName())).collect(Collectors.toList())
.forEach(System.out::println);
//44444
transactions.stream().map(item->item.getTrader().getName()).sorted().distinct().forEach(System.out::println);
//55555
// boolean b = transactions.stream().anyMatch(item -> item.getTrader().getCity() == "Milan");
// System.out.println(b);
//(6)
//transactions.stream().filter(item->item.getTrader().getCity()==("Cambridge")).map(item->item.getValue()).forEach(System.out::println);
//(7)
// Optional<Transaction> max = transactions.stream().max(((o1, o2) -> o1.getValue() - o2.getValue()));
// System.out.println(max);
// (8)
// Optional<Transaction> min = transactions.stream().min(((o1, o2) -> o1.getValue() - o2.getValue()));
// System.out.println(min);