欢迎关注作者博客
简书传送门
/**
* 外部迭代
*/
public void test1_1() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
for (int number : numbers){
System.out.println(number);
}
}
/**
* 内部迭代
*/
public void test1_2() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(new Consumer<Integer>() {
@Override
public void accept(Integer value) {
System.out.println(value);
}
});
}
/**
* java8 lambda进一步
*/
public void test1_3() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach((Integer value) -> System.out.println(value));
}
/**
* java8 lambda再进一步
*/
public void test1_4() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(value -> System.out.println(value));
}
/**
* java8 lambda再再进一步
*/
public void test1_5() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
numbers.forEach(System.out::println);
}
/**
* 普通排序
*/
public void test2_1() {
List<String> names = Arrays.asList("zhangsan", "wangwu", "lisi", "zhaoliu");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
List<Student> students = null;
Collections.sort(students, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getScore().compareTo(o1.getScore());
}
});
}
class Student {
private String name;
private String score;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScore() {
return score;
}
public void setScore(String score) {
this.score = score;
}
}
/**
* java8 lambda排序
*/
public void test2_2() {
List<String> names = Arrays.asList("zhangsan", "wangwu", "lisi", "zhaoliu");
List<Student> students = new ArrayList<>();
Collections.sort(names, (a, b) -> {
return b.compareTo(a);
});
Collections.sort(names, (a, b) -> b.compareTo(a));
Collections.sort(students, (a, b) -> b.getScore().compareTo(a.getScore()));
System.out.println(names);
System.out.println(students);
}
public void test3_1() {
TheInterface theInterface = () -> {};
System.out.println(theInterface.getClass().getInterfaces()[0]);
TheInterface2 theInterface2 = () -> {};
System.out.println(theInterface2.getClass().getInterfaces()[0]);
}
@FunctionalInterface
interface TheInterface {
void myMethod();
}
@FunctionalInterface
interface TheInterface2 {
void myMethod2();
}
public void test4_1() {
// 使用匿名内部类
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("start");
}
}).start();
// 使用lambda
new Thread(() -> System.out.println("start")).start();
}
public void test5_1() {
List<String> list = Arrays.asList("one","two","three");
list.forEach(item -> System.out.println(item.toUpperCase()));
List<String> list2 = new ArrayList<>();
list.forEach(item -> list2.add(item.toUpperCase()));
list2.forEach(item -> System.out.println(item));
}
public void test6_1() {
List<String> list = Arrays.asList("one","two","three");
list.stream().map(item -> item.toUpperCase()).forEach(item -> System.out.println(item));
list.stream().map(String::toUpperCase).forEach(item -> System.out.println(item));
}
/**
* Function测试类
*/
class FunctionTest {
public int compute(int a, Function<Integer, Integer> function) {
int result = function.apply(a);
return result;
}
public String convert(int a, Function<Integer, String> function) {
return function.apply(a);
}
}
public void test7_1() {
FunctionTest test = new FunctionTest();
System.out.println(test.compute(1, value -> {return 2 * value;}));
System.out.println(test.compute(2, value -> 5 + value));
System.out.println(test.compute(3, value -> value * value));
System.out.println(test.convert(5, value -> String.valueOf(value + "helloworld")));
}
static class FunctionTest2 {
public static void main(String[] args) {
FunctionTest2 test = new FunctionTest2();
// System.out.println(test.compute(2, value -> value * 3, value -> value * value)); // 12
// System.out.println(test.compute2(2, value -> value * 3, value -> value * value)); // 36
// System.out.println(test.compute3(1, 2, (value1, value2) -> value1 * value2)); // 2
// System.out.println(test.compute3(1, 2, (value1, value2) -> value1 / value2)); // 0.5
System.out.println(test.compute4(2, 3, (value1, value2) -> value1 + value2, value -> value * value)); // 25
}
public int compute(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(a);
}
public int compute2(int a, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(a);
}
public int compute3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
return biFunction.apply(a, b);
}
public int compute4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
return biFunction.andThen(function).apply(a, b);
}
}
static class Person {
private String username;
private Integer age;
public Person(String username, Integer age) {
this.username = username;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
static class PersonTest {
public static void main(String[] args) {
PersonTest test = new PersonTest();
Person p1 = new Person("zhangsan", 20);
Person p2 = new Person("lisi", 22);
Person p3 = new Person("wangwu", 25);
List<Person> peoples = Arrays.asList(p1, p2, p3);
List<Person> personResult1 = test.getPersonsByUsername("zhangsan", peoples);
personResult1.forEach(person -> System.out.println(person.getUsername()));
List<Person> personResult2 = test.getPersonsByAge(20, peoples);
personResult2.forEach(person -> System.out.println(person.getAge()));
List<Person> personResult3 = test.getPersonsByAge1(20, peoples);
personResult3.forEach(person -> System.out.println(person.getAge()));
List<Person> personResult4 = test.getPersonsByAge2(20, peoples, (age, personList) -> {
return personList.stream().filter(person -> person.getAge() > age).collect(Collectors.toList());
});
personResult4.forEach(person -> System.out.println(person.getAge()));
}
public List<Person> getPersonsByUsername(String username, List<Person> persons) {
return persons.stream().filter(person -> person.getUsername().equals(username)).collect(Collectors.toList());
}
public List<Person> getPersonsByAge(int age, List<Person> persons) {
return persons.stream().filter(person -> person.getAge() == age).collect(Collectors.toList());
}
public List<Person> getPersonsByAge1(int age, List<Person> persons) {
BiFunction<Integer, List<Person>, List<Person>> biFunction = (ageOfPerson, personList) -> {
return personList.stream().filter(person -> person.getAge() > ageOfPerson).collect(Collectors.toList());
};
return biFunction.apply(age, persons);
}
public List<Person> getPersonsByAge2(int age, List<Person> persons, BiFunction<Integer, List<Person>, List<Person>> biFunction) {
return biFunction.apply(age, persons);
}
}
static class PredicateTest {
public static void main(String[] args) {
Predicate<String> predicate = p -> p.length() > 5;
System.out.println(predicate.test("hello1"));
}
}
static class PredicateTest2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
PredicateTest2 predicateTest2 = new PredicateTest2();
predicateTest2.conditionFilter(list, item -> item % 2 == 0);
System.out.println("----------");
predicateTest2.conditionFilter(list, item -> item % 2 != 0);
System.out.println("----------");
predicateTest2.conditionFilter(list, item -> item > 5);
System.out.println("----------");
predicateTest2.conditionFilter(list, item -> item < 3);
System.out.println("----------");
predicateTest2.conditionFilter(list, item -> true);
System.out.println("----------");
predicateTest2.conditionFilter(list, item -> false);
System.out.println("----------");
predicateTest2.conditionAndFilter(list, item -> item > 5, item -> item % 2 == 0);
System.out.println("----------");
System.out.println(predicateTest2.isEqual("test").test("test"));
System.out.println("----------");
}
public void conditionFilter(List<Integer> list, Predicate<Integer> predicate) {
list.forEach(c -> {
if (predicate.test(c)) {
System.out.println(c);
}
});
}
public void conditionAndFilter(List<Integer> list, Predicate<Integer> predicate, Predicate<Integer> predicate2) {
list.forEach(c -> {
if (predicate.and(predicate2).test(c)) {
System.out.println(c);
}
});
}
public Predicate<String> isEqual(Object object) {
return Predicate.isEqual(object);
}
}
static class Student2 {
private String name = "zhangsan";
private Integer age;
public Student2() {
}
public Student2(String name, Integer age) {
this.name = name;
this.age = age;
}
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;
}
}
static class StudentTest {
public static void main(String[] args) {
Supplier<Student2> supplier = () -> new Student2();
System.out.println(supplier.get().getName());
System.out.println("--------------");
Supplier<Student2> supplier1 = Student2::new;
System.out.println(supplier1.get().getName());
}
}
/**BinaryOperator其父类是BiFunction;
* 主要提供大小比较的两个函数
*/
static class BinaryOperatorTest {
public static void main(String[] args) {
BinaryOperatorTest binaryOperatorTest = new BinaryOperatorTest();
System.out.println(binaryOperatorTest.compute(1, 2, (a, b) -> a + b));
System.out.println("------------------");
System.out.println(binaryOperatorTest.getShort("hello11111", "world", (a, b) -> a.length() - b.length()));
System.out.println(binaryOperatorTest.getShort("hello11111", "world", (a, b) -> a.charAt(0) - b.charAt(0)));
}
public int compute(int a, int b, BinaryOperator<Integer> binaryOperator) {
return binaryOperator.apply(a, b);
}
public String getShort(String a, String b, Comparator<String> compartor) {
return BinaryOperator.maxBy(compartor).apply(a, b);
}
}
static class OptionalTest {
public static void main(String[] args) {
// Optional optional = Optional.of(null);
Optional<String> optional = Optional.empty();
// if (optional.isPresent()) {
// System.out.println(optional.get());
// }
optional.ifPresent(item -> System.out.println(item)); // 推荐使用
System.out.println("--------------");
System.out.println(optional.orElse("world"));
System.out.println("--------------");
System.out.println(optional.orElseGet(() -> "nihao"));
}
}
static class OptionalTest2 {
public static void main(String[] args) {
Employee e = new Employee("zhangsan");
Employee e2 = new Employee("lisi");
Company c = new Company("company1", null);
List<Employee> employees = Arrays.asList(e, e2);
c.setEmployees(employees);
List<Employee> list = c.getEmployees();
// 赋值
Optional<Company> optional = Optional.ofNullable(c);
System.out.println(optional.map(theCompany -> theCompany.getEmployees()).orElse(Collections.emptyList()));
}
static class Employee {
private String name;
public Employee(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
static class Company {
private String name;
private List<Employee> employees;
public Company(String name, List<Employee> employees) {
this.name = name;
this.employees = employees;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
}
}
/**
* 方法引用实际上是个Lambda表达式的一种语法糖
* 我们可以将方法看作是一个【函数指针】,function pointer
* 方法引用共分为4类:
* 1、类名::静态方法名
* 2、引用名(对象名)::实例方法名
* 3、类名::实例方法名
* 4、构造方法引用:类名::new
*/
static class MethodReferenceTest {
public String getString(Supplier<String> supplier) {
return supplier.get() + "test";
}
public String getString2(String str, Function<String, String> function) {
return function.apply(str);
}
public static void main(String[] args) {
Student student = new Student("zhangsan", 10);
Student student1 = new Student("lisi", 90);
Student student2 = new Student("wangwu", 50);
Student student3 = new Student("zhaoliu", 40);
List<Student> students = Arrays.asList(student, student1, student2, student3);
students.sort((studentParam1, studentParam2) -> Student.compareStudentByScore(studentParam1, studentParam2));
students.forEach(stu -> System.out.println(stu.getScore()));
System.out.println("------------------------");
// 1、类名::静态方法名
students.sort(Student::compareStudentByName);
students.forEach(stu -> System.out.println(stu.getName()));
System.out.println("------------------------");
// 2、引用名(对象名)::实例方法名
StudentComparator sc = new StudentComparator();
students.sort(sc::compareStudentByName);
students.forEach(stu -> System.out.println(stu.getName()));
System.out.println("------------------------");
students.forEach(stu -> System.out.println(stu.getScore()));
System.out.println("------------------------");
// 3、类名::实例方法名
List<String> cities = Arrays.asList("anhui", "chongqing", "qingdao", "beijing");
Collections.sort(cities, (city1, city2) -> city1.compareToIgnoreCase(city2));
cities.forEach(c -> System.out.println(c));
System.out.println("------------------------");
students.sort(Student::compareByName);
students.forEach(stu -> System.out.println(stu.getName()));
System.out.println("------------------------");
students.sort(Student::compareByScore);
students.forEach(stu -> System.out.println(stu.getScore()));
System.out.println("------------------------");
Collections.sort(cities, String::compareToIgnoreCase);
cities.forEach(System.out::println);
System.out.println("------------------------");
MethodReferenceTest mrt = new MethodReferenceTest();
System.out.println(mrt.getString(String::new));
System.out.println(mrt.getString2("hello", String::new));
System.out.println("------------------------");
// 4、构造方法引用:类名::new
}
static class Student {
private String name;
private Integer score;
public Student(String name, Integer score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
public static int compareStudentByScore(Student s1, Student s2) {
return s1.getScore() - s2.getScore();
}
public static int compareStudentByName(Student s1, Student s2) {
return s1.getName().compareToIgnoreCase(s2.getName());
}
public int compareByScore(Student s) {
return this.getScore() - s.getScore();
}
public int compareByName(Student s) {
return this.getName().compareToIgnoreCase(s.getName());
}
}
static class StudentComparator {
public static int compareStudentByScore(Student s1, Student s2) {
return s1.getScore() - s2.getScore();
}
public int compareStudentByName(Student s1, Student s2) {
return s1.getName().compareToIgnoreCase(s2.getName());
}
}
}
/**
* Stream流
* 流由三个部分构成:
* 1、源
* 2、零个或多个中间操作
* 3、终止操作
*
* 流操作的分类:
* 1、惰性求值
* 2、及早求值
* stream.xxx().yyy().zzz().count();
* ----惰性求值-------及早求值--
*/
static class StreamTest1 {
public static void main(String[] args) {
Stream stream1 = Stream.of("hello", "world", "hello world");
String[] myArray = new String[]{"hello", "world", "hello world"};
Stream stream2 = Stream.of(myArray);
Stream stream3 = Arrays.stream(myArray);
List<String> list = Arrays.asList(myArray);
Stream stream4 = list.stream();
}
}
static class StreamTest2 {
public static void main(String[] args) {
IntStream.of(new int[]{5, 6, 7}).forEach(System.out::println);
System.out.println("-------");
IntStream.range(3, 8).forEach(System.out::println);
System.out.println("-------");
IntStream.rangeClosed(3, 8).forEach(System.out::println);
}
}
static class StreamTest3 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
System.out.println(list.stream().map(i -> i * 2).reduce(0, Integer::sum));
}
}