1. Lambda expression
1. Understand Lambda expressions
Lambda expression is a new syntax form starting with JDK 8
Function: Used to simplify the code writing of anonymous inner classes of functional interfaces.
Functional interface: An interface with one and only one abstract method.
public class Test{ public static void main(String[] args) { Student[] students = new Student[4]; students[0] = new Student("a",143.9,18); students[1] = new Student("b",123.3,13); students[2] = new Student("c",187.4,19); students[3] = new Student("d",155.2,18); Arrays.sort(students, (Student o1,Student o2)->{ return Double.compare(o1.getHeight(), o2.getHeight()); }); System.out.println(Arrays.toString(students)); } }
Take the code at the end of the previous section as an example to rewrite the compare method in the Comparator interface as Lambda.
Note: Most of the functional interfaces you will see in the future may have a @FunctionalInterface annotation on them. The interface with this annotation must be a functional interface.
2. Omission rules for Lambda expressions
1) The parameter type can be omitted.
2) If there is only one parameter, the parameter type can be omitted, and () can also be omitted.
3) If the method body code in the Lambda expression has only one line of code, you can omit the curly braces and omit the semicolon. At this time, if this line of code is a return statement, the return must be removed and not written.
public class Test{ public static void main(String[] args) { double[] arr3 = new double[]{99.8,22.6,100}; // Arrays.setAll(arr3, new IntToDoubleFunction(){ // @Override // public double applyAsDouble(int value) { // return BigDecimal.valueOf(arr3[value]).multiply(BigDecimal.valueOf(0.8)).doubleValue(); // } // }); Arrays.setAll(arr3, value -> BigDecimal.valueOf(arr3[value]).multiply(BigDecimal.valueOf(0.8)).doubleValue()); System.out.println(Arrays.toString(arr3)); // [79.84, 18.08, 80.0] } }
Rewrite the applyAsDouble method of the IntToDoubleFunction interface according to the omission rules
2. Stream stream
1. Understand Stream flow
Stream is a set of APIs newly added in JDK8, which can be used to manipulate data in collections or arrays.
Advantages: Stream streams are heavily combined with Lambda syntax style for programming, providing a more powerful and simpler way to operate data in collections or arrays. The code is simpler and more readable.
Example: Put the three-character names of people with the surname Zhang in the following collection into a new collection
public class Test { public static void main(String[] args) { List<String> names = new ArrayList<>(); Collections.addAll(names,"Zhang San","Wang Wu","Zhao Liu","Li Si","Zhang Tianhao"); System.out.println(names); // [Zhang San, Wang Wu, Zhao Liu, Li Si, Zhang Tianhao] List<String> list1 = new ArrayList<>(); for (String name : names) { if(name.startsWith("张") & amp; & amp; name.length() == 3) { list1.add(name); } } System.out.println(list1); // [Zhang Tianhao] List<String> list2 = names.stream() .filter(s -> s.startsWith("张")).filter(s -> s.length() == 3).collect(Collectors.toList()); System.out.println(list2); // [Zhang Tianhao] } }
2. Common operations of Stream streams
1) Get the Stream stream
public class Test { public static void main(String[] args) { // Get the Stream stream of the Collection collection List<String> list = new ArrayList<>(); Set<String> set = new HashSet<>(); Stream<String> s1 = list.stream(); Stream<String> s2 = set.stream(); // Get the Stream stream of the Map collection Map<String,Integer> map = new HashMap<>(); Set<String> keys = map.keySet(); Collection<Integer> values = map.values(); Set<Map.Entry<String,Integer>> entries = map.entrySet(); Stream<String> s3 = keys.stream(); Stream<Integer> s4 = values.stream(); Stream<Map.Entry<String,Integer>> s5 = entries.stream(); // Get the Stream stream of the array Integer[] arr = {1,2,3,4,5}; Stream<Integer> s6 = Arrays.stream(arr); Stream<Integer> s7 = Stream.of(arr); } }
Note: 1) Obtaining the Stream stream of the Map collection requires first extracting the key-value pairs as objects
2) There are two methods for extracting Stream from an array. Both methods are available.
2) Collect Stream stream
Convert the result of the Stream operation back to the collection or array and return it
public class Test { public static void main(String[] args) { Double[] arr = new Double[]{100.0,99.9,89.2}; Object[] arr1 = Arrays.stream(arr).toArray(); System.out.println(Arrays.toString(arr1)); Double[] arr2 = Arrays.stream(arr).toArray(len -> new Double[len]); System.out.println(Arrays.toString(arr2)); ArrayList<Student> students = new ArrayList<>(); students.add(new Student("cxk",25,176.8)); students.add(new Student("wyb",35,188.8)); students.add(new Student("fzc",15,170.1)); students.add(new Student("zth",5,162.2)); // Find several people whose height is greater than 175 List<Student> list = students.stream().filter(s -> s.getHeight() > 175).collect(Collectors.toList()); Set<Student> set = students.stream().filter(s -> s.getHeight() > 175).collect(Collectors.toSet()); Map<String,Double> map = students.stream().filter(s -> s.getHeight() > 175).collect(Collectors.toMap(Student::getName,Student::getHeight)); System.out.println(list); System.out.println(set); System.out.println(map); } }
Note: 1) When collecting a Stream into an array, an Object array is returned; if you want to get an array of a specified type, you need to add a return standard to the toArray method
2) When collecting a Stream into a Map collection, you need to add a return standard to the toMap method. If there are duplicate elements at this time, you need to use the distinct method to remove the duplicate elements before collecting them.
3. Common methods of Stream streams
Important note: The Stream object can only be called or operated once, and cannot be called or operated repeatedly
1) Intermediate method of Stream
It means that after the call is completed, a new Stream will be returned and can continue to be used (chain programming is supported)
public class Test { public static void main(String[] args) { Double[] scores = new Double[]{100.0,98.7,99.9,66.6}; // Filter numbers greater than 90 Arrays.stream(scores).filter(s -> s > 90).forEach(System.out::println); Double[] scores2 = new Double[]{58.0,60.0,59.9}; // Combine two streams into one Stream<Double> s3 = Stream.concat(Arrays.stream(scores),Arrays.stream(scores2)); s3.forEach(System.out::println); ArrayList<Student> students = new ArrayList<>(); students.add(new Student("cxk",25,176.8)); students.add(new Student("cxk",25,176.8)); students.add(new Student("wyb",35,188.8)); students.add(new Student("fzc",15,170.1)); students.add(new Student("zth",5,162.2)); // Sort the output in ascending order by height students.stream().sorted((o1,o2) -> Double.compare(o1.getHeight(),o2.getHeight())).forEach(System.out::println); //Intercept the first three information students.stream().limit(3).forEach(System.out::println); //Intercept the information of the last two students.stream().skip(students.size() - 2).forEach(System.out::println); // Get all people's names students.stream().map(s->s.getName()).forEach(System.out::println); // Remove duplicate information students.stream().distinct().forEach(System.out::println); } }
Note: When removing objects with different addresses but different contents, the distinct method can override the equals method and hascode method of the class to which the object belongs.
2) Stream’s termination method
It means that after the call is completed, the new Stream will not be returned and the stream cannot be used anymore.
public class Test { public static void main(String[] args) { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("cxk",25,176.8)); students.add(new Student("wyb",35,188.8)); students.add(new Student("fzc",15,170.1)); students.add(new Student("zth",5,162.2)); // Find out how many people are taller than 170cm System.out.println(students.stream().filter(s -> s.getHeight() > 170).count()); // 3 // Find the tallest person System.out.println(students.stream().max((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get()); // Find the shortest person System.out.println(students.stream().min((o1, o2) -> Double.compare(o1.getHeight(), o2.getHeight())).get()); } }
Note: 1) The rules that need to be reformulated for the max and min methods must be in ascending order, otherwise the results will be inverted.
2) The max and min methods return an Optional container, and the result needs to be retrieved through the get method.
The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 137669 people are learning the system