preface

Lambda expressions are the most important new feature released in Java 8. Lambda allows functions to be passed as arguments to a method, i.e. functions can be passed as arguments to a method. Using Lambda expressions makes our code more compact and easier to understand.

This article only records some examples used in my work. It will not introduce some underlying principles of Lambda, such as functional interfaces and method references. If you need to understand these knowledge, please refer to the relevant materials.Copy the code

The preparatory work

To facilitate subsequent examples, we need to define an entity class first:

package com.learn.lambda; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor public class LambdaDemo { private String item; private Integer statNum; private String itemValue; /** * Private Object extendInfo; public LambdaDemo(String item, Integer statNum) { this.item = item; this.statNum = statNum; }}Copy the code

Initialize sample data:

private static List<LambdaDemo> demoList = new ArrayList<>();
    static {
        LambdaDemo demo1 = new LambdaDemo("001",100);
        LambdaDemo demo2 = new LambdaDemo("002",200);
        LambdaDemo demo3 = new LambdaDemo("003",300);
        LambdaDemo demo4 = new LambdaDemo("004",400);
        LambdaDemo demo5 = new LambdaDemo("005",500);
        LambdaDemo demo6 = new LambdaDemo("006",600);
        LambdaDemo demo7 = new LambdaDemo("007",700);
        LambdaDemo demo8 = new LambdaDemo("008",800);
        LambdaDemo demo9 = new LambdaDemo("009",900);
        LambdaDemo demo10 = new LambdaDemo("010",1000);
        demoList.add(demo1);
        demoList.add(demo2);
        demoList.add(demo3);
        demoList.add(demo4);
        demoList.add(demo5);
        demoList.add(demo6);
        demoList.add(demo7);
        demoList.add(demo8);
        demoList.add(demo9);
        demoList.add(demo10);
    }
Copy the code

Up to this point, the preparatory work has been basically completed.

The sample

A List collection is converted to a Map collection

If there is no duplicate key, you can use the following method

Public static void listToMap(){Map<String, Integer> collect = demoList.stream().collect(Collectors.toMap(LambdaDemo::getItem, LambdaDemo::getStatNum)); collect.forEach((key,value)-> System.out.println(key+":"+value)); // If the value is empty, you can check Map<String, Integer> Map = demolist.stream ().collect(LambdaDemo::getItem, p -> p.getStatNum() == null ? 0 : p.getStatNum())); System.out.println(map); }Copy the code

If the map is converted to duplicate keys, an error will occur. Set the sample data to duplicate keys.

LambdaDemo demo1 = new LambdaDemo("001",100);
LambdaDemo demo2 = new LambdaDemo("001",200);
Copy the code

Executing the above code again will result in the following error:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 100
	at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
	at java.util.HashMap.merge(HashMap.java:1254)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
Copy the code

Add the values of duplicate keys. If the values are strings, separate them with commas. Perform corresponding operations based on actual business requirements.

/ * * * the list into the Map will solve the problem of duplicate key values * values in * / public static void listToMapSolveDuplicateKey () {Map < String, Integer> collect = demoList.stream().collect(Collectors.toMap(LambdaDemo::getItem, LambdaDemo::getStatNum,(oleValue,newValue)->oleValue+newValue)); collect.forEach((key,value)-> System.out.println(key+":"+value)); }Copy the code

The output is as follows:

001:300 // If the value of 001 is 300, the values of the duplicate key values are added 003:300 004:400 005:500 006:600 007:700 008:800 009:900 010:1000Copy the code

You can also override:

/ * * * the list into the Map will solve the problem of duplicate key values * value * / public static void listToMapSolveDuplicateKey2 () {Map < String, Integer> collect = demoList.stream().collect(Collectors.toMap(LambdaDemo::getItem, LambdaDemo::getStatNum,(oleValue,newValue)->newValue)); collect.forEach((key,value)-> System.out.println(key+":"+value)); }Copy the code

The key is which value to use. OleValue is the value of the first key, and newValue is the value of the second key.

(oleValue,newValue)->newValue)
(oleValue,newValue)->oleValue)
Copy the code

List< String < LambdaDemo >>

Use groupingBy to group

Map<String, List< LambdaDemo >> collect = demoList.stream().collect(Collectors.groupingBy(LambdaDemo::getItem));
Copy the code

Use the entity class as a value value

Map<String, Integer> collect = demoList.stream().collect(Collectors.toMap(LambdaDemo::getItem, lambdaDemo->lambdaDemo));
Copy the code

Or the following form

Map<String, Integer> collect = demoList.stream().collect(Collectors.toMap(LambdaDemo::getItem, Function.identity()));
Copy the code

Evaluates the sum of some values in an object

*/ public static void listSum(){int sum = demoList.stream().mapToInt(LambdaDemo::getStatNum).sum(); System.out.println(sum); }Copy the code

In addition to mapToInt methods, there are mapToDouble, mapToLong and other methods. It can be used on demand.

List is converted to a string

Commas can also be replaced with other related symbols as required

/ / public static void listToString(){String value = demolist.stream ().map(lambdaDemo -> String.valueOf(lambdaDemo.getItem())).collect(Collectors.joining(",")); System.out.println(value); }Copy the code

List is converted to list

The list in the sample data holds objects. We can extract items from the object and convert them into a new List

Public static void listToList(){list <String> stringList = demoList.stream().map(LambdaDemo::getItem).collect(Collectors.toList()); stringList.forEach(System.out::println); }Copy the code

Delete the data

Using Lambda to delete data is also handy:

Public static void removeData(){demolist.removeIf (lambdaDemo-> lambdademo.getitem ().equals("001")); demoList.forEach(lambdaDemo -> System.out.println(lambdaDemo.getItem())); }Copy the code

The sorting

To scramble the statNum data in the sample data, sort it as follows:

Public static void sortData() {// demoist.sort (Comparator.comparing(LambdaDemo::getStatNum)); demoList.forEach(lambdaDemo -> System.out.println(lambdaDemo.getStatNum())); System.out.println("----------"); / / reverse demoList. Sort (Comparator.com paring (LambdaDemo: : getStatNum). Reversed ()); demoList.forEach(lambdaDemo -> System.out.println(lambdaDemo.getStatNum())); }Copy the code

JSONArray sorting

JSONArray array = mtd.getJSONArray("XXXX");
array.sort(Comparator.comparing(obj -> ((JSONObject) obj).getString("XX")));
Copy the code

filter

Filtering is also common, such as filtering out records with statNum equal to 500

Public static void filter(){Stream<LambdaDemo> lambdaDemoStream = demoist.stream ().filter(LambdaDemo -> lambdaDemo.getStatNum() == 500); lambdaDemoStream.forEach(lambdaDemo -> { System.out.println(lambdaDemo.getStatNum()); }); }Copy the code
The above is just a part of the examples I use in my current work. It is intended to make a simple record for timely reference when I keep a memo. I will update from time to time, welcome to add in the comments section!Copy the code