内置核心四大函数式接口
@Test
public void testFunction() {
Function<String, Integer> f = new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return s.hashCode();
}
};
Function<String, Integer> f1 = s -> {
return s.hashCode();
};
System.out.println(f.apply("wqe"));
}
@Test
public void testPredicate() {
Predicate<Integer> p = new Predicate<Integer>() {
@Override
public boolean test(Integer integer) {
return integer > 0;
}
};
Predicate<Integer> p1 = s -> {
return 1 > s;
};
System.out.println(p.test(1));
testConsumer();
}
@Test
public void testConsumer() {
Consumer<String> c = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println("消费" + s);
}
};
Consumer<String> c1 = s -> {
System.out.println("消费" + s);
};
c.accept("new");
}
@Test
public void testSupplier() {
Supplier<String> s = new Supplier() {
@Override
public String get() {
return "qwe";
}
};
Supplier<String> s1 = () -> {
return "qwe";
};
System.out.println(s.get());
}
Stream流
public class StreamDemo {
public static void main(String[] args){
User u1 = new User(11, "a", 23);
User u2 = new User(12, "b", 24);
User u3 = new User(13, "c", 22);
User u4 = new User(14, "d", 28);
User u5 = new User(16, "e", 26);
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
list.stream().filter(user -> {
return user.getId() % 2 == 0;
}).filter(user -> {
return user.getAge() > 24;
}).map(user -> {
return user.getName().toUpperCase();
}).sorted((o1, o2) -> {
return o2.compareTo(o1);
}).limit(1).forEach(System.out::println);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private int age;
}