The github repository is used to share knowledge about Java, including Java basics, MySQL, Spring Boot, MyBatis, Redis, RabbitMQ, etc. Welcome to mention pr and star!

Github address: github.com/Tyson0314/J…

If Github is not available, access the Gitee repository.

Gitee address: gitee.com/tysondai/Ja…

Functional programming

Object-oriented programming: In object-oriented languages, everything is an object. If you want to call a function, the function must belong to a class or object and then be called using the class or object. Object-oriented programming involves many more lines of code that may be repetitive.

        Runnable runnable = new Runnable() {
            @Override
            public void run(a) {
                System.out.println("do something..."); }};Copy the code

Functional programming: in some programming languages, such as js and c++, we can simply write a function and call it as needed.

Lambda expressions

Prior to Java8, sort strings using the Collections sort method was written:

List<String> names = Arrays.asList("dabin"."tyson"."sophia");

Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        returnb.compareTo(a); }});Copy the code

Java8 recommends lambda expressions to simplify this approach.

List<String> names = Arrays.asList("dabin"."tyson"."sophia");

Collections.sort(names, (String a, String b) -> b.compareTo(a)); // Make it simple
names.sort((a, b) -> b.compareTo(a)); // The Java compiler can use type inference to determine the type of the argument
Copy the code

You can see that using the lambda representation makes the code shorter and easier to read.

Functional interface

Functional Interface: an Interface that contains only one abstract method. Only functional interfaces can be abbreviated to Lambda expressions. @functionalinterface defines the class as a FunctionalInterface, and if you add a second abstract method, the compiler immediately throws an error.

@FunctionalInterface
interface Converter<F.T> {
    T convert(F from);
}

public class FunctionalInterfaceTest {
    public static void main(String[] args) {
        Converter<String, Integer> converter = (from) -> Integer.valueOf(from);
        Integer converted = converter.convert("666");
        System.out.println(converted);
    }
    /** * output * 666 */
}
Copy the code

Built-in functional interfaces

Java 8 adds the @functionalInterface annotation to both Comparator and Runnable to support Lambda expressions.

Predicate assertion

A functional interface that specifies an input parameter type and returns a Boolean value. To combine a complex logical judgment.

Predicate<String> predicate = (s) -> s.length() > 0;

predicate.test("dabin"); // true
Copy the code

Comparator

Java8 upgrades the Comparator to a functional interface that simplifies the code using the lambda representation.

/ * * *@description:
 * @author: Programmer Dabin *@time: "* / 2021-09-05
public class ComparatorTest {
    public static void main(String[] args) {
        Comparator<Person> comparator = Comparator.comparing(p -> p.firstName);

        Person p1 = new Person("dabin"."wang");
        Person p2 = new Person("xiaobin"."wang");

        / / print - 20
        System.out.println(comparator.compare(p1, p2));
        / / print 20System.out.println(comparator.reversed().compare(p1, p2)); }}class Person {
    public String firstName;
    public String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName; }}Copy the code

Consumer

The Consumer interface takes a generic parameter and calls Accept to do a series of Consumer operations on that parameter.

Consumer source code:

@FunctionalInterface
public interface Consumer<T> {

    void accept(T t);
    
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return(T t) -> { accept(t); after.accept(t); }; }}Copy the code

Example 1:

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-05 suffering justly * /
public class ConsumerTest {
    public static void main(String[] args) {
        Consumer<Integer> consumer = x -> {
            int a = x + 6;
            System.out.println(a);
            System.out.println("DaBin" + a);
        };
        consumer.accept(660);
    }
    /** * output * 666 */
}
Copy the code

Example 2: In a stream, do some operations on incoming arguments, mainly for forEach, and a series of business operations on incoming arguments.

// CopyOnWriteArrayList
public void forEach(Consumer<? super E> action) {
    if (action == null) throw new NullPointerException();
    Object[] elements = getArray();
    int len = elements.length;
    for (int i = 0; i < len; ++i) {
        @SuppressWarnings("unchecked") E e = (E) elements[i];
        action.accept(e);
    }
}

CopyOnWriteArrayList<Integer> list = new CopyOnWriteArrayList<>();
list.add(1);
list.add(2);
//forEach needs to pass in the Consumer argument
list
    .stream()
    .forEach(System.out::println);
list.forEach(System.out::println);
Copy the code

Example 3: Use of the addThen method.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-05 23:59 * /
public class ConsumersTest {
    public static void main(String[] args) {
        Consumer<Integer> consumer1 = x -> System.out.println("first x : " + x);
        Consumer<Integer> consumer2 = x -> {
            System.out.println("second x : " + x);
            throw new NullPointerException("throw exception second");
        };
        Consumer<Integer> consumer3 = x -> System.out.println("third x : " + x);

        consumer1.andThen(consumer2).andThen(consumer3).accept(1);
    }
    /** * output * first x : 1 * second x : 1 * Exception in thread "main" java.lang.NullPointerException: throw exception second * at com.dabin.java8.ConsumersTest.lambda$main$1(ConsumersTest.java:15) * ... * /
}
Copy the code

Stream

Use java.util.Stream to perform various operations on a collection containing one or more elements, leaving the original collection unchanged and returning the new collection. Flow operations can only be performed on classes that implement the java.util.Collection interface. Map does not support Stream streams. Stream supports both synchronous and concurrent execution.

The Filter to Filter

The Filter entry is the Predicate, which is used to Filter out the set elements we need. The original set is the same. The following code filters out nameList strings that do not start with bin.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("DaBin 1");
        nameList.add("DaBin 2");
        nameList.add("aaa");
        nameList.add("bbb");

        nameList
                .stream()
                .filter((s) -> s.startsWith("DaBin"))
                .forEach(System.out::println);
    }
    /** * output */
}
Copy the code

Sorted order

Natural sort, do not change the original set, return the sorted set.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest1 {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("DaBin 3");
        nameList.add("DaBin 1");
        nameList.add("DaBin 2");
        nameList.add("aaa");
        nameList.add("bbb");

        nameList
                .stream()
                .filter((s) -> s.startsWith("DaBin"))
                .sorted()
                .forEach(System.out::println);
    }
    /** * output ** output */
}
Copy the code

Reverse sort:

nameList
    .stream()
    .sorted(Comparator.reverseOrder());
Copy the code

Sort a field of the element:

list.stream().sorted(Comparator.comparing(Student::getAge).reversed());
list.stream().sorted(Comparator.comparing(Student::getAge));
Copy the code

The Map transformation

Uppercase each string.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest2 {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("aaa");
        nameList.add("bbb");

        nameList
                .stream()
                .map(String::toUpperCase)
                .forEach(System.out::println);
    }
    /** * output * AAA * BBB */
}
Copy the code

Match Match

Verify that any string in nameList begins with bin.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest3 {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("DaBin 1");
        nameList.add("DaBin 2");

        boolean startWithDabin =
                nameList
                    .stream()
                    .map(String::toUpperCase)
                    .anyMatch((s) -> s.startsWith("DaBin"));

        System.out.println(startWithDabin);
    }
    /** * output * true */
}
Copy the code

Count Count

Count the total number of elements in the stream and return type long.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest4 {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("DaBin 1");
        nameList.add("DaBin 2");
        nameList.add("aaa");

        long count =
                nameList
                    .stream()
                    .map(String::toUpperCase)
                    .filter((s) -> s.startsWith("DaBin"))
                    .count();

        System.out.println(count);
    }
    /** * output * 2 */
}
Copy the code

Reduce

Similar to splicing. It is possible to implement the reduction of list to a value. Its return type is Optional.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:22 * /
public class StreamTest5 {
    public static void main(String[] args) {
        List<String> nameList = new ArrayList<>();
        nameList.add("DaBin 1");
        nameList.add("DaBin 2");

        Optional<String> reduced =
                nameList
                        .stream()
                        .sorted()
                        .reduce((s1, s2) -> s1 + "#" + s2);

        reduced.ifPresent(System.out::println);
    }
    /** * output */
}
Copy the code

flatMap

FlatMap is used to join multiple streams into a single Stream.

In the following example, convert several small lists to one large list.

/ * * *@descriptionConvert several small lists to one large list. *@author: Programmer Dabin *@time: the 2021-09-06 00:28 * /
public class StreamTest6 {
    public static void main(String[] args) {
        List<String> team1 = Arrays.asList("DaBin 1"."DaBin 2"."DaBin 3");
        List<String> team2 = Arrays.asList("DaBin 4"."DaBin 5");

        List<List<String>> players = new ArrayList<>();
        players.add(team1);
        players.add(team2);

        List<String> flatMapList = players.stream()
                .flatMap(pList -> pList.stream())
                .collect(Collectors.toList());

        System.out.println(flatMapList);
    }
    /** * output * [db1, db2, db2, db3, db3] */
}
Copy the code

In the following example, the elements in the Words array are split by characters, and then the characters are unduplicated.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:35 * /
public class StreamTest7 {
    public static void main(String[] args) {
        List<String> words = new ArrayList<String>();
        words.add("Dabin is the strongest");
        words.add("DaBin 666");

        // Split the elements of the words array by characters, then unduplicate the characters
        List<String> stringList = words.stream()
                .flatMap(word -> Arrays.stream(word.split("")))
                .distinct()
                .collect(Collectors.toList());
        stringList.forEach(e -> System.out.print(e + ","));
    }
    /** * output *, 6, */
}
Copy the code

Parallel-Streams

The parallel flow. Stream supports both sequential and parallel streams. Sequential stream operations are single-threaded operations, serialized streams do not bring performance improvements, usually we use multiple threads to perform tasks in parallel, processing speed is faster.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-06 00:05 * /
public class StreamTest7 {
    public static void main(String[] args) {
        int max = 100;
        List<String> strs = new ArrayList<>(max);
        for (int i = 0; i < max; i++) {
            UUID uuid = UUID.randomUUID();
            strs.add(uuid.toString());
        }

        List<String> sortedStrs = strs.stream().sorted().collect(Collectors.toList());
        System.out.println(sortedStrs);
    }
    /** * output * [029be6d0-e77e-4188-b511-f1571cdbf299, 02d97425-b696-483a-80c6-e2ef51c05d83, 0632f1e9-e749-4bce-8bac-1cf6c9e93afa, ...] * /
}
Copy the code

Map collections

Java8 adds some handy methods for map operations

1. Remove elements using the removeIf() method.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-07 00:03 * /
public class MapTest {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1."dabin1");
        map.put(2."dabin2");

        // delete key-value pairs that do not contain 1map.values().removeIf(value -> ! value.contains("1"));

        System.out.println(map);
    }
    /** * output * {1=dabin1} */
}
Copy the code

2. PutIfAbsent (key, value) If the specified key does not exist, put it in.

/ * * *@description:
 * @author: Programmer Dabin *@time: the 2021-09-07 00:08 * /
public class MapTest1 {
    public static void main(String[] args) {

        Map<Integer, String> map = new HashMap<>();
        map.put(1."DaBin 1");

        for (int i = 0; i < 3; i++) {
            map.putIfAbsent(i, "DaBin" + i);
        }
        map.forEach((id, val) -> System.out.print(val + ","));
    }
    /** * output output */
}
Copy the code

3. Map transformation.

/ * * *@author: Programmer Dabin *@time: the 2021-09-07 08:15 * /
public class MapTest2 {
    public static void main(String[] args) {
        Map<String, Integer> map = new HashMap<>();
        map.put("1".1);
        map.put("2".2);

        Map<String, String> newMap = map.entrySet().stream()
                .collect(Collectors.toMap(e -> e.getKey(), e -> "DaBin" + String.valueOf(e.getValue())));

        newMap.forEach((key, val) -> System.out.print(val + ","));
    }
    /** * output * 2, */
}
Copy the code

4. Map traversal.

/ * * *@author: Programmer Dabin *@time: the 2021-09-07 08:31 * /
public class MapTest3 {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1."DaBin 1");
        map.put(2."DaBin 2");

        1 / / way
        map.keySet().forEach(k -> {
            System.out.print(map.get(k) + ",");
        });

        2 / / way
        map.entrySet().iterator().forEachRemaining(e -> System.out.print(e.getValue() + ","));

        3 / / way
        map.entrySet().forEach(entry -> {
            System.out.print(entry.getValue() + ",");
        });

        4 / / way
        map.values().forEach(v -> {
            System.out.print(v + ","); }); }}Copy the code

The resources

https://juejin.im/post/5c3d7c8a51882525dd591ac7#heading-16

Finally, we share a Github repository, which contains more than 200 classic computer books, including C language, C++, Java, Python, front-end, database, operating system, computer network, data structure and algorithm, machine learning, programming life, etc. The warehouse is being updated

Github address: github.com/Tyson0314/j…

If Github is not available, access the Gitee repository.

Gitee address: gitee.com/tysondai/ja…