In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "what is the principle and function of lambda in java". In daily operation, I believe that many people have doubts about the principle and function of lambda in java. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "what is the principle and function of lambda in java?" Next, please follow the editor to study!
I. introduction
The biggest feature of java8 is the introduction of Lambda expressions, that is, functional programming, which can pass behavior. The summary is: using immutable values and functions, the function processes the immutable value and maps it to another value.
2. Java important functional interface 1. What is a functional interface?
A function interface is an interface that has only one abstract method and is used as a type for an Lambda expression. For classes decorated with @ FunctionalInterface annotations, the compiler detects whether the class has only one abstract method or interface, otherwise, it will report an error. There can be multiple default methods, static methods.
1.1 the common functional interface that comes with java8.
Public class Test {public static void main (String [] args) {Predicate predicate = x-> x > 185; Student student = new Student ("9 dragons", 23,175); System.out.println ("is 9 dragons taller than 185s? : "+ predicate.test (student.getStature ()); Consumer consumer = System.out::println; consumer.accept (" fate is not determined by me "); Function function = Student::getName; String name = function.apply (student); System.out.println (name); Supplier supplier = ()-> Integer.valueOf (BigDecimal.TEN.toString ()) System.out.println (supplier.get ()); UnaryOperator unaryOperator = uglily->! uglily; Boolean apply2 = unaryOperator.apply (true); System.out.println (apply2); BinaryOperator operator = (x, y)-> x * y; Integer integer = operator.apply (2,3); System.out.println (integer); test (()-> "I am a functional interface for demonstration") } / * demonstrate that the custom functional interface uses * * @ param worker * / public static void test (Worker worker) {String work = worker.work (); System.out.println (work);} public interface Worker {String work ();}} / / is the height of dragon higher than 185s? False// fate is determined by me / / 9 dragons / / 10//false//6// I am a functional interface for demonstration
The above demonstrates the use of the lambda interface and the customization and use of a functional interface. Next, let's take a look at how efficiently java8 encapsulates functional interfaces into streams to help us process collections.
Note: this way of writing lambda expressions in the Student::getName example is called a method reference. The format is ClassNmae::methodName. Isn't it amazing? java8 is so charming.
Examples: all the examples in this article are based on the following three classes. OutstandingClass: class; Student: student; SpecialityEnum: specialty.
1.2 lazy evaluation and early evaluation
Lazy evaluation: only Stream is described, and the result of the operation is also Stream, which is called lazy evaluation. Lazy evaluation can be used as a chain like the builder pattern, and then use early evaluation to get the final result.
Early evaluation: getting the final result instead of Stream is called early evaluation.
2. Commonly used stream 2.1 collect (Collectors.toList ())
Convert the stream to list. There are also toSet (), toMap () and so on. Evaluate as soon as possible.
Public class TestCase {public static void main (String [] args) {List studentList = Stream.of (new Student ("Luffy", 22,175), new Student ("Red hair", 40,180), new Student ("White Beard", 50,185). Collectors.toList (); System.out.println (studentList) } / / output result / / [Student {name=' Lufei', age=22, stature=175, specialities=null}, / / Student {name=' Red hair', age=40, stature=180, specialities=null}, / / Student {name=' White Beard', age=50, stature=185, specialities=null}] 2.2 filter
As the name implies, it plays the role of filtering. Inside is the Predicate interface. Lazy evaluation.
For example, we screen out the students whose height is less than 180.
Public class TestCase {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student ("Luffy", 22,175); students.add ("Red hair", 40,180); students.add (new Student ("White Beard", 50,185); List list = students.stream () .filter (stu-> stu.getStature ()
< 180) .collect(Collectors.toList()); System.out.println(list); }}//输出结果//[Student{name='路飞', age=22, stature=175, specialities=null}]2.3 map 转换功能,内部就是Function接口。惰性求值Public class TestCase {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student (Luffy, 22,175)); students.add (new Student (Red hair, 40,180); students.add (White Beard, 50,185)) List names = students.stream (). Map (student-> student.getName ()). Coach (Collectors.toList ()); System.out.println (names);}} / / output result / / [Luffy, red hair, white beard]
In the example, the student object is converted to a String object to get the name of the student.
2.4 flatMap
Merge multiple Stream into a single Stream. Lazy evaluation
Public class TestCase {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student (Luffy, 22,175)); students.add (new Student (Red hair, 40,180); students.add (White Beard, 50,185)) List studentList = Stream.of (students, asList (new Student ("Ace", 25,183), new Student ("Riley", 48,176)) .flatMap (students1-> students1.stream ()) .flatMap (Collectors.toList ()); System.out.println (studentList) } / / output result / / [Student {name=' Luffy', age=22, stature=175, specialities=null}, / / Student {name=' Red hair', age=40, stature=180, specialities=null}, / / Student {name=' White Beard', age=50, stature=185, specialities=null}, / / Student {name=' Ace', age=25, stature=183, specialities=null}, / / Student {name=' Riley', age=48, stature=176, specialities=null}]
Call the static method of Stream.of to convert the two list to Stream, and then merge the two streams into one through flatMap.
2.5 max and min
We often find the maximum or minimum value in the set, so it is convenient to use the stream. Evaluate as soon as possible.
Public class TestCase {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student (Luffy, 22,175)); students.add (new Student (Red hair, 40,180); students.add (White Beard, 50,185)) Optional max = students.stream () .max (Comparator.comparing (stu-> stu.getAge ()); Optional min = students.stream () .min (Comparator.comparing (stu-> stu.getAge (); / / determine whether there is a value if (max.isPresent ()) {System.out.println (max.get ()) } if (min.isPresent ()) {System.out.println (min.get ());} / output result / / Student {name=' White Beard', age=50, stature=185, specialities=null} / / Student {name=' Lufei, age=22, stature=175, specialities=null}
Max and min receive a Comparator (in the example, you use the static function that comes with java8, which only needs to be passed in to compare the values. And returns an Optional object, a new class from java8, specifically to prevent null pointer exceptions thrown by null
You can use max.isPresent () to determine whether there is a value; you can use max.orElse (new Student ()), which uses the given value when the value is null; or you can use max.orElseGet (()-> new Student ()); you need to pass in a lambda expression of Supplier.
2.6 count
Statistical function is generally used in combination with filter, because we can first filter out what we need and then make statistics. Evaluate as soon as possible
Public class TestCase {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student ("Luffy", 22,175); students.add ("Red hair", 40,180); students.add (new Student ("White Beard", 50,185); long count = students.stream (). Filter (S1-> s1.getAge ()
< 45).count(); System.out.println("年龄小于45岁的人数是:" + count); }}//输出结果//年龄小于45岁的人数是:22.7 reduce reduce 操作可以实现从一组值中生成一个值。在上述例子中用到的 count 、 min 和 max 方法,因为常用而被纳入标准库中。事实上,这些方法都是 reduce 操作。及早求值。 public class TestCase { public static void main(String[] args) { Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) ->Acc+ x); System.out.println (reduce);}} / / output result / / 10
We can see that reduce receives an accumulator with an initial value of 0, and adds the value to the accumulator in turn, and the final value of the accumulator is the final result.
Advanced collection classes and collectors 3.1 are converted to values
Collector, a general structure that generates complex values from a stream. Just pass it to the collect method and all streams can use it. The standard class library already provides some useful collectors, which are statically imported from the java.util.stream.Collectors class in the following sample code.
Public class CollectorsTest {public static void main (String [] args) {List students1 = new ArrayList (3); students1.add (new Student ("Luffy", 23,175)); students1.add ("Red hair", 40,180); students1.add ("White Beard", 50,185); OutstandingClass ostClass1 = new OutstandingClass ("Class one", students1) / / copy students1 and remove a student List students2 = new ArrayList (students1); students2.remove (1); OutstandingClass ostClass2 = new OutstandingClass ("Class two", students2); / / convert ostClass1 and ostClass2 to Stream Stream classStream = Stream.of (ostClass1, ostClass2); OutstandingClass outstandingClass = biggestGroup (classStream); System.out.println ("the largest class is" + outstandingClass.getName ()) System.out.println ("average age of class one is:" + averageNumberOfStudent (students1));} / * * get the class with the largest number of students * / private static OutstandingClass biggestGroup (Stream outstandingClasses) {return outstandingClasses.collect (maxBy (ostClass-> ostClass.getStudents (). Size () .orElseGet (OutstandingClass::new) } / * calculate average age * / private static double averageNumberOfStudent (List students) {return students.stream (). Collect (averagingInt (Student::getAge));} / / output results / / the class with the largest number of students is: the average age of class one is 37.666666666666664
MaxBy or minBy is to find the maximum and minimum values.
3.2 convert to block
A common stream operation is to decompose it into two sets, which Collectors.partitioningBy implements for us to receive a Predicate functional interface.
The sample students are divided into two sets that can sing and can't sing.
Public class PartitioningByTest {public static void main (String [] args) {/ / omit the initialization Map listMap of List students = students.stream () .collect (Collectors.partitioningBy (student-> student.getSpecialities (). Contains (SpecialityEnum.SING));}} 3.3data packets
Data grouping is a more natural way to split data, and unlike dividing the data into ture and false, you can use any value to group the data. Collectors.groupingBy receives a Function for conversion.
As shown in the figure, we use groupingBy to group groups into circles, triangles, and squares according to the order.
Example: grouping students according to their first specialty
Public class GroupingByTest {public static void main (String [] args) {/ / omit the initialization Map listMap of List students = students.stream (). Collect (Collectors.groupingBy (student-> student.getSpecialities (). Get (0));}}
The group by operation in Collectors.groupingBy is the same as in SQL.
3.4 string concatenation
What do you do if you put all the students' names together? Usually only one StringBuilder can be created, circular stitching. Using Stream, using Collectors.joining () is simple and easy.
Public class JoiningTest {public static void main (String [] args) {List students = new ArrayList (3); students.add (new Student (Luffy, 22,175)); students.add (new Student (Red hair, 40,180); students.add (White Beard, 50,185)) String names = students.stream () .map (Student::getName) .birthday (Collectors.joining (",", "[", "[", "])); System.out.println (names);}} / / output result / / [Luffy, red hair, white beard]
Joining takes three parameters, the first is the delimiter, the second is the prefix, and the third is the Terminator. It is also possible not to pass in the parameter Collectors.joining (), which is called direct splicing.
IV. Summary
This article mainly describes the common methods and flows from the actual use, using java8 can clearly express what you want to do, and the code is very concise. The main purpose of this example is to explain that it is relatively simple. You can use java8 to ReFactor your existing code and understand the mysteries of lambda.
The Stream mentioned in this article needs to be combined to play a greater function, chain call is very charming, according to their own business to do it.
At this point, the study of "what is the principle and function of lambda in java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.