JavaSE pickup record

1, New features of JDK8

1. lambda expression

Lambda expressions can be used to replace the interface implementation with only one abstract function. Bid farewell to anonymous internal classes. Look at the code
It is more concise and easy to understand. Lambda expressions also improve the operations of iteration, traversal and data filtering of sets and frameworks.

characteristic:

  • Functional programming
  • Automatic inference of parameter type
  • Less code, concise

When you write a functional interface, you can add this annotation to help check whether it is a functional interface

@FunctionalInterface

Method reference:

public class Lambda1 {
    static String getName(){
        return "LuFei";
    }
    public static void main(String[] args) {
        //Method 1: lambda expression
        Supplier<String> s1 = ()-> Lambda1.getName();
        System.out.println(s1.get());
        //Method 2: method reference
        Supplier<String> s2 = Lambda1::getName;
        System.out.println(s2.get());
    }
}

jdk built-in functional interface

Supplier represents an output
Consumer represents an input
BiConsumer represents two inputs
Function represents one input and one output (generally, input and output are of different types)
UnaryOperator represents one input and one output (input and output are of the same type)
BiFunction represents two inputs and one output (generally input and output are of different types)
BinaryOperator represents two inputs and one output (input and output are of the same type)

Classification of method references

typegrammarCorresponding labda expression
Static method referenceclassName::staticMethod(args)->className.staticMethod(args)
Instance method referenceinstance::method(args)->instance.mehtod
Object method referenceclassName::method(instance,args)->className.method(args)
Construction method referenceclassName::new(args)->new className(args)

2,stream api

stream performance is not as good as for loop

IntStream is a subclass of Stream

Stream is divided into source, intermediate operation and termination operation

(1) 5 ways to generate stream

1) Array generation stream

String[] strs = {"a","b","c","d"};
Stream<String> strsStream = Stream.of(strs);
strsStream.forEach(System.out::println);

Output:

a
b
c
d

2) Generate stream from collection

List<String> strs = Arrays.asList("1", "2", "3", "4", "5");
Stream<String> strStream = strs.stream();
strStream.forEach(System.out::println);

Output:

1
2
3
4
5

3)generate

//Infinite output 1
Stream<Integer> generate = Stream.generate(() -> 1);
generate.forEach(System.out::print);
System.out.println();

Output:

11111111111... Infinite output 1

4)iterate

//Generate a stream of 1 to 10
Stream<Integer> iterate = Stream.iterate(1, x -> x + 1);
iterate.limit(10).forEach(System.out::println);

Output:

1
2
3
4
5
6
7
8
9
10

5) stream generated by other API s

String str = "abcdef";
IntStream chars = str.chars();
chars.forEach(System.out::println);

Output:

97
98
99
100
101
102

(2) Other examples

1)limit

//Limit output 9 1
Stream<Integer> generate = Stream.generate(() -> 1);
generate.limit(9).forEach(System.out::print);

Output:

111111111

2)filter

Filter out even numbers:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);       
list.stream().filter((x) -> x % 2 == 0).forEach(System.out::println);

Output:

2
4
6
8

Select and sum even numbers:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
int sum = list.stream().filter(x -> x % 2 == 0).mapToInt(x -> x).sum();
System.out.println(sum);

Output:

20

3)max

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
Optional<Integer> max = list.stream().max((a, b) -> a - b);
System.out.println(max.get());

Output:

9

4)min

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(list.stream().min((a, b) -> a - b).get());

Output:

1

5)findAny

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(list.stream().filter(x -> x % 2 == 0).findAny().get());

Output:

2

6)findFirst

//If there is no element after the filter, findFirst will report an error
System.out.println(list.stream().filter(x -> {
    System.out.println("implement" + x);
    return x % 2 == 0;
}).findFirst().get());

Output:

Execution 1
Execution 2
2

7) Sort

List<String> strings = Arrays.asList("java", "C#", "javascript", "python", "scala");
strings.stream().sorted().forEach(System.out::println);

Output:

C#
java
javascript
python
scala

Custom collation

List<String> strings = Arrays.asList("java", "C#", "javascript", "python", "scala");
strings.stream().sorted((a, b) -> b.length() - a.length()).forEach(System.out::println);

Output:

javascript
python
scala
java
C#

8)collect

//Filter the collection and return to the collection
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> collect = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList());
collect.forEach(System.out::println);

Output:

2
4
6
8

9)distinct

//You can also use toSet() for de duplication
List<Integer> integers = Arrays.asList(1, 2, 12, 12, 1, 2, 4, 5, 4);
List<Integer> collect1 = integers.stream().distinct().collect(Collectors.toList());
collect1.forEach(System.out::println);

Output:

1
2
12
4
5

10)skip

//Print 21 to 30
Stream.iterate(1, x -> x + 1).limit(50).skip(20).limit(10).forEach(System.out::println);

Output:

21
22
23
24
25
26
27
28
29
30

11)sum

String str2 = "11,22,33,44,55";
System.out.println(Stream.of(str2.split(",")).mapToInt(x -> Integer.valueOf(x)).sum());
System.out.println(Stream.of(str2.split(",")).mapToInt(Integer::valueOf).sum());

Output:

165
165

12) Create a set of custom objects

class Person{
    String name;

    public Person() {}

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                '}';
    }
}
String str3 = "java,C#,scala,python";
Stream.of(str3.split(",")).map(Person::new).forEach(System.out::println);

Output:

Person{name='java'}
Person{name='C#'}
Person{name='scala'}
Person{name='python'}

13)peek

//Print out each value in str2 and output the sum
String str2 = "11,22,33,44,55";
System.out.println(Stream.of(str2.split(",")).peek(System.out::println).mapToInt(Integer::valueOf).sum());

Output:

11
22
33
44
55
165

14)allMatch

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
System.out.println(list.stream().allMatch(x -> x > 0));

Output:

true

To be continued....

Keywords: Java

Added by mustatin on Mon, 20 Sep 2021 01:10:59 +0300