Tips

I roughly around the lamda, stream, method introduction, Optional usage these aspects to analyze. In the first half, I will briefly talk about Lamda and Stream. Others will be updated later. Welcome correction!

1. Some new features and benefits of JDK8

In Jdk 8, the following points are roughly summarized. Personally, I think the most important ones are the lamda expression and stream, and the others are not unimportant. hh

First: You can define normal methods in an interface.

Second point: LAMDA expressions (emphasis).

Number three: it’s a functional interface.

Fourth: the application of methods and constructors.

Fifth: Stream (emphasis) interface.

So what are his benefits?

In a professional sense, it simplifies our calls to anonymous inner classes to simplify the code. If you want to be leaner, you can introduce the Lamda expression + method to make the code leaner

2. Lamda expressions

2.1 Lamda Default and common methods

The first one is that since jdk1.8, static and default method bodies are supported in interfaces and do not need to be overridden. The code is attached below!

IDefaultLamda interface

public interface IDefaultLamda {

    void add();
  
    /** * JDK 8 provides default methods, and some may report errors, because JKD is not larger than 1.8 */
    default void defaultGet(){
        System.out.println("An added normal method body is defined in the interface");
    }

    /**
     * 静态方法
     */
    static void staticDelete(){
        System.out.println("The interface defines a common method body to delete."); }}Copy the code

DefaultLamdaImpl implementation class

/** * implements the interface, but there is no requirement to implement default and static methods
public class DefaultLamdaImpl implements IDefaultLamda {
    @Override
    public void add() {
        System.out.println("Overrides the add method."); }}Copy the code

The test class, TestDefault, contains the results

public class TestDefault {
    public static void main(String[] args) {
        DefaultLamdaImpl defaultLamda = new DefaultLamdaImpl();
        defaultLamda.add();
        defaultLamda.defaultGet();
        IDefaultLamda.staticDelete();
		/ / = = = = = = = = = = = = = = = = = = = printing results = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
		// Overrides the add method
		// An added common method body is defined in the interface
		// The interface defines a common method body to delete}}Copy the code

2.2 Lamda Expression Specification (Function Interface definition)

Using the LAMDA expression, it actually relies on the function interface. So let’s talk about functional interfaces

  1. Only one abstract method is allowed in an interface.
  2. Define methods in the Object class in the function interface. That is, some methods in the superclass can be overridden. ToString (), equls method)
  3. Default or static methods are used.
  4. The annotation @functionalInterface identifies the interface as a function interface. Some Runnable interfaces are annotated with @functionalInterface

2.3 Basic syntax of Lamda expressions

Grammar explanation:

() : parameter list. -> : Partition. {} : method body.

Let’s demonstrate a method call with no arguments versus a method call with arguments.

Function interface (provided with no arguments) :

@FunctionalInterface
public interface ILamdaTest1 {
    void getSize();
}
Copy the code

Function interface (provided with parameters) :

@FunctionalInterface
public interface ILamdaTest2 {
    String getName(int a,int b,int c);
}
Copy the code

Not participating in calls with arguments:

public static void main(String[] args) {
 	/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- no written arguments START -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /
    // The first method is more concise
    ((ILamdaTest1) () -> System.out.println("No-argument expression 1 used in the Lamda expression")).getSize();
    // The second way
    ILamdaTest1 lamdaTest =()-> System.out.println("No-argument expression 2 used in the Lamda expression");
    lamdaTest.getSize();
    / / = = = = = = = = = = = = = = = = = = = = = = = = = = = printing results = = = = = = = = = = = = = = = = = = = = = = = = = =
    // Use the no-argument expression 1 to the Lamda expression
	// Use the no-argument expression 2 to the Lamda expression
    / * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- no arguments spelled the END -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /




 	/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- have written arguments start -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /

    // The first is more concise
    String name = ((ILamdaTest2) (a, b, c) -> a + "-" + b + "-" + c).getName(2.3.4);
    System.out.println("Return the value 1 obtained with an argument:"+name);
    // The second way
    ILamdaTest2 lamdaTest2s = (a, b,c) -> a+"Add"+b+"Add"+c;
    System.out.println("Return the value 2 obtained with a parameter:"+lamdaTest2s.getName(5.10.5));

    / / = = = = = = = = = = = = = = = = = = = = = = = = = = = printing results = = = = = = = = = = = = = = = = = = = = = = = = = =
    // Return the obtained value 1:2-3 -4
	// Return the obtained value 2:5 + 10 + 5
    / * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- have written arguments END -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * /
}
Copy the code

2.4 Use Lamda expressions to traverse the collection

@Test
public void testForeach(){
	// First create a list collection
	List<Integer> list = new ArrayList<>();
	list.add(12);
	list.add(23);
	list.add(67);
	list.add(78);
	list.add(85);
	list.add(45);
	list.add(46);
	list.add(28);
	list.add(19);
	list.add(99);
	System.out.println("Current list size:"+list.size());

    // Use foreach to iterate
    list.forEach(new Consumer<Integer>() {
        @Override
        public void accept(Integer integer) {
            System.out.println("Use the normal foreach method:"+integer); }});/ / using lambda
    list.forEach(integer -> System.out.println(integer));
}
Copy the code

2.5 Use Lamda expressions to sort collections

First we create an entity class, UserEntity:, generate its own parameter constructor, generate get and set methods, override toString, and then test

public class UserEntity {
    private String name;
    private Integer age;
}
Copy the code

SortingTest:

public class SortingTest {
    public static void main(String[] args) {
        List<UserEntity> list = new ArrayList<>();
        list.add(new UserEntity("zhangsan1".54));
        list.add(new UserEntity("zhangsan2".25));
        list.add(new UserEntity("zhangsan3".18));
        list.add(new UserEntity("zhangsan4".19));
        list.add(new UserEntity("zhangsan5".35));
        list.add(new UserEntity("zhangsan6".59));
        /* The first demonstration */
        /*list.sort(new Comparator
      
       () { @Override public int compare(UserEntity o1, UserEntity o2) { return o1.getAge() - o2.getAge(); }}); * /
      

        /* The second demonstration */
        // list.sort((o1, o2) -> o1.getAge() - o2.getAge());

        /* The third demonstration */
        list.sort(Comparator.comparingInt(UserEntity::getAge));

        // Let's iterate againlist.forEach(d -> System.out.println(d)); }}Copy the code

Running result:

UserEntity{name='zhangsan3', age=18} 
UserEntity{name='zhangsan4', age=19}
UserEntity{name='zhangsan2', age=25}
UserEntity{name='zhangsan5', age=35}
UserEntity{name='zhangsan1', age=54}
UserEntity{name='zhangsan6', age=59} 
Copy the code

3 the Stream flow

Stream, which can iterate, filter, sort, page, deduplicate, and so on in a very convenient and compact form. We can see two ways to create streams (stream() and parallelStream()).

What's the difference between serial stream and parallel stream?

A serial stream we can think of as a single thread, a single thread to process. Parallel flow can be understood as multiple threads to process. Therefore, it is known that the efficiency of parallel streams is higher than that of serial streams.

Stream a process of a Stream?

2. Create a Stream ———- 3. Intermediate operations (filter, sorted, and LIMIT) ———- 4. Terminate operations (foreach (traversal), Collect (transformation), min, Max, allMatch (condition))

Below I respectively cut out the use of lamda and not using lamda writing pictures, cut out is for the people who do not know how to write lamda expressions, you can use anonymous inner class writing, and then through the idea into lamda~~~~, note that there are text instructions in the screenshot oh.

3.1 Convert List to Set using Stream

First, create an entity class StreamEntity, override toString, construct, and generate get and set methods yourself, and then test

public class StreamEntity {
    private String name;
    private Integer age;
}
Copy the code
public static void main(String[] args) {
        List<StreamEntity> list = new ArrayList<>();
        list.add(new StreamEntity("zhangsan1".12));
        list.add(new StreamEntity("zhangsan2".234));
        list.add(new StreamEntity("zhangsan3".54));
        list.add(new StreamEntity("zhangsan4".23));
        list.add(new StreamEntity("zhangsan5".8));
        list.add(new StreamEntity("zhangsan6".39));
        list.add(new StreamEntity("zhangsan7".29));
        list.add(new StreamEntity("zhangsan7".29));
        
        // Convert it to a set. Note that there is no duplication here, because the stored object addresses are different
      	Set<StreamEntity> collect = list.stream().collect(Collectors.toSet());
        collect.forEach(data-> System.out.println(data));
    }
Copy the code

3.2 Set deduplication and underlying implementation principles

The map Set is based on equals () and Hashcode () to prevent duplicate keys. First of all, new returns two objects with the same value. If you don’t override equals, it returns false

    @Test
    public void setDuplicateRemovalOne(){
        StreamEntity streamEntity1 = new StreamEntity("zhangsan7".29);
        StreamEntity streamEntity2 = new StreamEntity("zhangsan7".29);
        /* I have overwritten equals () to determine if their values are equal. Returns false*/ if the equals method is not overridden
        System.out.println(streamEntity1.equals(streamEntity2));  // Print the result to true

    }
Copy the code

Override equals in SreamEntity. Here we are comparing their contents. So, no matter how new you are, as long as the contents are the same, return true

	/** * Override the object method */
    public boolean equals(Object obj){
        if (obj instanceof StreamEntity){
            return name.equals(((StreamEntity)obj).name) && age == (((StreamEntity)obj).age);
        }else {
            return false; }}Copy the code

What if it’s a map set that has the same key, but different values? So here we’re going to rewrite the hashCode. Override the hashCode method in the SreamEntity

    /** * Rewrite hashCode *@return* /
    public int hashCode(){
        return name.hashCode();
    }
Copy the code
    @Test
    public void setDuplicateRemovalTwo(){
        StreamEntity streamEntity1 = new StreamEntity("zhangsan7".29);
        StreamEntity streamEntity2 = new StreamEntity("zhangsan7".29);

        // Override hashCode to remove the redo
        HashMap<Object.Object> objectHashMap = new HashMap<>();
        objectHashMap.put(streamEntity1,"one");
        objectHashMap.put(streamEntity2,"two");
        objectHashMap.forEach((k,v)-> System.out.println(k+","+v));
    }
Copy the code

Print result:

3.3 Use Stream to convert List into Map

Here is a first explanation, not in the form of lamDA expression, but in the development, is sure to be converted into lamDA expression. Do not post the code for the moment, more typing…

Unused lambda: Using lambda:

Final result:

3.4 Using Stream to do Reduce

Unused lambda: Using lambda:

Final result:

3.5 Calculate the maximum value (Max) and minimum value (min) by Stream

It’s the same thing. If we call it min instead of Max, we’re minimizing itUnused lambda:

Using lambda:It’s replaced with a Comparator

Final result:

3.6 Stream Match usage (anyMatch and allMatch)

It is used to match, return true if there is a match, return fasle if there is no match.Unused lambda: Using lambda: Final result:

3.7 Stream Filter

Unused lambda: Using lambda: Final result:

3.8 Stream page (limit)

3.9 Stream sorts collections (sorted)

Unused lambda:

Using lambda:

Final result: