inotgo.com


Tool version compatibility problem
Suppose a scenario : Find the ones that meet the conditions Hero
This tutorial will start with Common method , Anonymous class , as well as Lambda These ways , Gradually introduce Lambda Concept of
Correct

This video is interpretive , So I hope you have read the content of this knowledge point , And after writing the corresponding code , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning



20 branch 39 second
This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers



Step 1 : Common method   
Step 2 : Anonymous class method   
Step 3 : Lambda Way   
Step 4 : set up eclipse To support Lambda   
Step 5 : From anonymous classes to Lambda expression   
Step 6 : Anonymous Methods   
Step 7 : Lambda Disadvantages of   
Step 8 : practice -Comparator   
Step 9 : answer -Comparator   

Use a common method , stay for Condition judgment in loop traversal , Filter out the data that meets the conditions

hp>100 && damage<50
 Common method
package lambda; import java.util.ArrayList; import java.util.List; import java.util.Random; import charactor.Hero; public class TestLambda { public static void main(String[] args) { Random r = new Random(); List<Hero> heros = new ArrayList<Hero>(); for (int i = 0; i < 10; i++) { heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100))); } System.out.println(" Initialized collection :"); System.out.println(heros); System.out.println(" Filter out hp>100 && damange<50 Hero of "); filter(heros); } private static void filter(List<Hero> heros) { for (Hero hero : heros) { if(hero.hp>100 && hero.damage<50) System.out.print(hero); } } }
package charactor; public class Hero implements Comparable<Hero>{ public String name; public float hp; public int damage; public Hero(){ } public Hero(String name) { this.name =name; } // initialization name,hp,damage The construction method of public Hero(String name,float hp, int damage) { this.name =name; this.hp = hp; this.damage = damage; } @Override public int compareTo(Hero anotherHero) { if(damage<anotherHero.damage) return 1; else return -1; } @Override public String toString() { return "Hero [name=" + name + ", hp=" + hp + ", damage=" + damage + "]\r\n"; } }
First prepare an interface HeroChecker, Provide a test(Hero) method
Then through anonymous classes , Implement this interface

HeroChecker checker = new HeroChecker() {
public boolean test(Hero h) {
return (h.hp>100 && h.damage<50);
}
};

Then call filter, Pass this checker Go in and judge , This way is very much like through Collections.sort On a Hero Set sorting , Need to pass one Comparator Anonymous class objects of the same .

 Anonymous class method
package lambda; import java.util.ArrayList; import java.util.List; import java.util.Random; import charactor.Hero; public class TestLambda { public static void main(String[] args) { Random r = new Random(); List<Hero> heros = new ArrayList<Hero>(); for (int i = 0; i < 5; i++) { heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100))); } System.out.println(" Initialized collection :"); System.out.println(heros); System.out.println(" Using anonymous classes , Filter out hp>100 && damange<50 Hero of "); HeroChecker checker = new HeroChecker() { @Override public boolean test(Hero h) { return (h.hp>100 && h.damage<50); } }; filter(heros,checker); } private static void filter(List<Hero> heros,HeroChecker checker) { for (Hero hero : heros) { if(checker.test(hero)) System.out.print(hero); } } }
package lambda; import charactor.Hero; public interface HeroChecker { public boolean test(Hero h); }
use Lambda Filter out the data

filter(heros,(h)->h.hp>100 && h.damage<50);

Also call filter method , Pass anonymous class objects from the previous step , It becomes a way to pass on Lambda The expression goes in

h->h.hp>100 && h.damage<50


What do you think Lambda The expression seems hard to understand , It's actually very simple , The next step explains how to start from an anonymous class a little Evolved into Lambda expression
Lambda Way
package lambda; import java.util.ArrayList; import java.util.List; import java.util.Random; import charactor.Hero; public class TestLamdba { public static void main(String[] args) { Random r = new Random(); List<Hero> heros = new ArrayList<Hero>(); for (int i = 0; i < 5; i++) { heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100))); } System.out.println(" Initialized collection :"); System.out.println(heros); System.out.println(" use Lamdba The way , Filter out hp>100 && damange<50 Hero of "); filter(heros,h->h.hp>100 && h.damage<50); } private static void filter(List<Hero> heros,HeroChecker checker) { for (Hero hero : heros) { if(checker.test(hero)) System.out.print(hero); } } }
Step 4 :

set up eclipse To support Lambda

edit top fracture
If your eclipse Be able to recognize Lambda, Then you can skip this chapter .
Because Lambda yes JDK8 The content of , except JDK Need to use 1.8 Beyond the above version ( stay JDK Environment variable configuration What you download is 1.8 Yes ), Also need to eclipse Set the compiler to 1.8 To be able to recognize Lambda.

Setting method :
Menu ->Window->Preferences->Java-Compiler->Compiler compliance leve: Set to 1.8 that will do
 set up eclipse To support Lambda
Step 5 :

From anonymous classes to Lambda expression

edit top fracture
Lambda Expressions can be thought of as anonymous classes, a little Evolved
1. The normal way to write anonymous classes

HeroChecker c1 = new HeroChecker() {
public boolean test(Hero h) {
return (h.hp>100 && h.damage<50);
}
};

2. Remove the outer shell
Keep only Method parameters and Method body
Add a symbol between the parameter and the method body ->

HeroChecker c2 = (Hero h) ->{
return h.hp>100 && h.damage<50;
};


3. hold return and {} Remove

HeroChecker c3 = (Hero h) ->h.hp>100 && h.damage<50;


4. hold Parameter types and parentheses are removed ( When there is only one parameter , To remove the parentheses )

HeroChecker c4 = h ->h.hp>100 && h.damage<50;


5. hold c4 Pass it in as a parameter

filter(heros,c4);


6. Pass the expression directly

filter(heros, h -> h.hp > 100 && h.damage < 50);
package lambda; import java.util.ArrayList; import java.util.List; import java.util.Random; import charactor.Hero; public class TestLamdba { public static void main(String[] args) { Random r = new Random(); List<Hero> heros = new ArrayList<Hero>(); for (int i = 0; i < 5; i++) { heros.add(new Hero("hero " + i, r.nextInt(1000), r.nextInt(100))); } System.out.println(" Initialized collection :"); System.out.println(heros); System.out.println(" Using anonymous classes , Filter out hp>100 && damange<50 Hero of "); // The normal way to write anonymous classes HeroChecker c1 = new HeroChecker() { @Override public boolean test(Hero h) { return (h.hp > 100 && h.damage < 50); } }; // hold new HeroChcekcer, Method name , Method returns type information // Keep only method parameters and method bodies // Add a symbol between the parameter and the method body -> HeroChecker c2 = (Hero h) -> { return h.hp > 100 && h.damage < 50; }; // hold return and {} Remove HeroChecker c3 = (Hero h) -> h.hp > 100 && h.damage < 50; // hold Parameter types and parentheses are removed HeroChecker c4 = h -> h.hp > 100 && h.damage < 50; // hold c4 Pass it in as a parameter filter(heros, c4); // Pass the expression directly filter(heros, h -> h.hp > 100 && h.damage < 50); } private static void filter(List<Hero> heros, HeroChecker checker) { for (Hero hero : heros) { if (checker.test(hero)) System.out.print(hero); } } }
With Anonymous class Compare concepts ,
Lambda Actually Anonymous Methods , This is a Take the method as a parameter Programming ideas for transmission .

Although the code is written like this

filter(heros, h -> h.hp > 100 && h.damage < 50);

But ,Java Will be behind , Quietly , Restore all this to Anonymous class method .
introduce Lambda expression , Will make the code more compact , Instead of interfaces and anonymous classes flying around .
Lambda Although expressions bring simplicity to the code , But it also has its limitations .
1. Poor readability , With wordy But Clear Compared with the anonymous class code structure ,Lambda Once the expression becomes longer , It's hard to understand
2. Inconvenient for debugging , It's hard to Lambda Add debugging information to the expression , Such as log
3. Version support ,Lambda Expression in JDK8 Support for... Only started in version , If the system uses a previous version , Consider the stability of the system , Not willing to upgrade , Then you can't use .

Lambda It is more suitable for short business code , Not suitable for complex systems , Will increase maintenance costs .
Step 8 :

practice -Comparator

edit top fracture   Wrong posture , get half the results with double the effort ! Click to see the correct posture for the exercise
hold Comparator -Comparator Code in Chapter , According to From anonymous classes to Lambda expression Steps for , Rewrite as Lambda expression
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Before looking at the answers , Try to finish it yourself first , See the answer when you encounter a problem , The harvest will be more
Viewing this answer will cost 4 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Viewing this answer will cost 4 Points , You currently have a total of Point integral . It doesn't cost extra points to see the same answer . Points increase method Or One time purchase JAVA Intermediate total 0 One answer ( Total required 0 Integral )
Account not activated Account not activated , Limited functionality . Please click activate
This video is interpretive , So I hope you have read the content of this answer , Watch with questions , Only in this way can we gain more . It is not recommended to watch the video at the beginning

4 branch 10 second This video uses html5 Play mode , If it cannot be played normally , Please upgrade your browser to the latest version , Recommend Firefox ,chrome,360 browser . If thunderbolt is installed , Play the video and show the direct download status , Please adjust Thunderbolt system settings - Basic settings - Start - Monitor all browsers ( Remove this option ). chrome of Video download Plug-in will affect playback , as IDM etc. , Please close or switch other browsers


package collection; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; import charactor.Hero; public class TestCollection { public static void main(String[] args) { Random r =new Random(); List<Hero> heros = new ArrayList<Hero>(); for (int i = 0; i < 10; i++) { heros.add(new Hero("hero "+ i, r.nextInt(100), r.nextInt(100))); } System.out.println(" Initialized collection :"); System.out.println(heros); // Anonymous class Comparator<Hero> c = new Comparator<Hero>() { @Override public int compare(Hero h1, Hero h2) { return h1.hp>=h2.hp?1:-1; } }; //Lambda expression c = (Hero h1, Hero h2)-> { return h1.hp>=h2.hp?1:-1; }; // Remove return And braces c = (Hero h1, Hero h2)->h1.hp>=h2.hp?1:-1; // Remove Parameter type c = (h1, h2)->h1.hp>=h2.hp?1:-1; // There are two parameters , Can't remove parentheses Collections.sort(heros,c); // Directly Lambda The expression is passed in as an argument Collections.sort(heros,(h1, h2)->h1.hp>=h2.hp?1:-1); System.out.println(heros); } }


The official account of programming , Follow and get the latest tutorials and promotions in real time , thank you .


Q & A area    
2021-08-17 answer
logiczqr




Comparator -Comparator Code in Chapter , According to the evolution from anonymous class to Lambda Steps of expression , Rewrite as Lambda expression
 System.out.println(" use lambda expression :");
		TreeSet<Integer> ts2 = new TreeSet<Integer>((o1,o2)->o1 >= o2?-1 : 1);
		for(int i = 0; i < 10; i++){
			ts2.add((int)(Math.random() * 100));
		}
		System.out.println(" The set sorted in reverse order ");
		System.out.println(ts2);
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-07-25 practice - Comparator
Mono




Comparator -Comparator Code in Chapter , According to the evolution from anonymous class to Lambda Steps of expression , Rewrite as Lambda expression
Random r = new Random();
		List<Hero> heros = new ArrayList<>();

		for (int i = 0; i <10; i++) {
			//  Random instantiation hero of hp and damage
        	heros.add(new Hero("hero-" + i, r.nextInt(100), r.nextInt(100)));
        }
		System.out.println(" Initialized collection :");
		System.out.println(heros);
		Collections.sort(heros,(h1,h2) -> (h1.damage >= h2.damage)?1 : -1);

		System.out.println(" The collection sorted by damage value ");
		System.out.println(heros);
 
               





The answer has been submitted successfully , Auditing . Please My answer Check the answer record at , thank you
answer Or code please Fill in at least one , If you have a problem , Please ask again , Otherwise, the webmaster may not see





2021-02-22 If filtered by damage What's wrong with sorting ?
2020-09-08 and ES6 The arrow function of is very similar to = =
2020-06-06 How do you know h What is it ?


Too many questions , Page rendering is too slow , To speed up rendering , Only a few questions are displayed on this page at most . also 19 Previous questions , please Click to view

Please... Before asking questions land
The question has been submitted successfully , Auditing . Please My question Check the question record at , thank you
about JAVA Intermediate -Lambda-Hello Lambda Your questions

Try to provide Screenshot code and Abnormal information , Help to analyze and solve problems . You can also enter this station QQ Group communication : 496725845
Ask questions and try to provide complete code , Environment description , The more conducive to the recurrence of the problem , The faster your question can be answered .
Have questions about the code in the tutorial , Please provide which step , Which line is in doubt , This makes it easy to quickly locate the problem , Improve the speed at which questions are answered
In the thousands of questions that already exist , A considerable proportion , Because of the use of and webmaster Different versions of the development environment Resulting in , For example jdk, eclpise, idea, mysql,tomcat Wait, the version of the software is inconsistent .
Please use the same version as the webmaster , You can save yourself a lot of learning time . The webmaster sorted out the software versions used in teaching , It's all here , Convenient for everyone to download : /k/helloworld/helloworld-version/1718.html

Upload screenshot