Focus on the public number “AI coder” to receive 2021 the latest interview materials, the public number to reply to the “source”, to obtain the source code of this project

Recently, I often use lambada expressions in projects, but I can’t remember them. They are always in Baidu, and I forget them after I write them, which feels very time-consuming. This time, I will take some time to save some examples of lambada processing sets (de-duplication, grouping, summation, list to map, etc.), so that I don’t have to look for them everywhere. I can also share them with students. In addition, I also share with you some of the pits encountered when using lambada, all the code is ready to use!! This document is continuously updated…

Examples demonstrate

Commodity entity

@Data

@AllArgsConstructor

public class GoodInfo {

    private String mallSource;

    private String skuNo;

    private int price;

    private int monthCount;

}

Copy the code

The sorting

Collection sorting is often used in projects. Here we take sorting by sales as an example

   List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Sort from smallest to largest in positive order of sales

    goodInfos.sort(Comparator.comparing(GoodInfo::getMonthCount));

// Sort by volume in reverse order

    goodInfos.sort(Comparator.comparing(GoodInfo::getMonthCount).reversed());

Copy the code

Max/min/sum

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



For example, goodinfos.stream ().filter(). Max must check whether the number of sets after filter is not empty, otherwise the Max get method will report an error

    GoodInfo hotGoodInfo = goodInfos.stream().max(Comparator.comparing(GoodInfo::getMonthCount)).get();

// Get the lowest price

    GoodInfo lowPriceGoodInfo = goodInfos.stream().min(Comparator.comparing(GoodInfo::getMonthCount)).get();

// Calculate the total price of goods

    int sum = goodInfos.stream().mapToInt(person -> person.getPrice()).sum();

// Find the average price

    double avg = goodInfos.stream().mapToInt(person -> person.getPrice()).average().getAsDouble();

Copy the code

traverse

   List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Iterate over all commodity ids

    goodInfos.forEach(

        goodInfo -> {

          System.out.println(goodInfo.getSkuNo());

        });

Copy the code

A collection of entities to a collection of individual attributes

Will have such a demand in our project, I need to extract a certain attributes in the collection, and then assembled into a collection, the usual practice is to create a string set first, and then through the original collection, take out data, into the string in the collection, although also can achieve the function, but not too trival, now using a line lambada expression can be done:

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Turn the list into a map of attributes

    List<String> skuNos = goodInfos.stream().map(goodInfo -> goodInfo.getSkuNo()).collect(Collectors.toList());

Copy the code

Entity collection returns to map

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Convert list to map with key as commodity ID

    Map<String, GoodInfo> map = goodInfos.stream().collect(Collectors.toMap(GoodInfo::getSkuNo, goodInfo -> goodInfo));

Copy the code

A collection of entities is grouped by an attribute

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Group goods by source

    Map<String, List<GoodInfo>> map = goodInfos.stream().collect(Collectors.groupingBy(GoodInfo::getMallSource));

Copy the code

Filter data (remember to receive)

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Filter items whose price is greater than 300

// Todo filter must be set to receive, otherwise there is no filter



    List<GoodInfo> collect =

        goodInfos.stream()

            .filter(goodInfo -> goodInfo.getPrice() > 300)

            .collect(Collectors.toList());

    collect.forEach(

        goodInfo -> {

          System.out.println(goodInfo.getPrice());

        });

Copy the code

Weight removal (two methods are optional)

Method 1

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Use the treeset set to implement the de-weight. The set receiver must be used, otherwise there is no de-weight

    List<GoodInfo> goodInfos1 =

        goodInfos.stream()

            .collect(

                Collectors.collectingAndThen(

                    Collectors.toCollection(

                        () -> new TreeSet<>(Comparator.comparing(o -> o.getSkuNo()))),

                    ArrayList::new));

Copy the code

Method 2 map deduplication

public static void main(String[] args) {

    List<GoodInfo> goodInfos = Arrays.asList();

    goodInfos.add(new GoodInfo("tb"."tb_1112312312", 199, 100000));

    goodInfos.add(new GoodInfo("tb"."tb_23534231231", 399, 10));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_1110080098", 299, 100));

    goodInfos.add(new GoodInfo("jd"."jd_412313123", 99, 10000000));

    goodInfos.add(new GoodInfo("pdd"."pdd_354532431", 599, 1));

    goodInfos.add(new GoodInfo("pdd"."pdd_1423124131", 499, 10));



// Use map to remove weights

    List<GoodInfo> goodInfos2 =

        goodInfos.stream()

            .filter(distinctByKey(goodInfo -> goodInfo.getSkuNo()))

            .collect(Collectors.toList());

  }



public static <T> Predicate<T> distinctByKey(Function<? super T, ? > keyExtractor) {

    Map<Object, Boolean> seen = new ConcurrentHashMap<>();

    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;

  }

Copy the code

In the pit of

A pit

  • Error message: Java. Util. NoSuchElementException: No value to the present

  • Solution: Generally, this error occurs when Max /min or other operations are used after filter operation, and then get method is called. As a result, no data can be obtained, an error is reported. Therefore, it is recommended to check the data after filter operation, and proceed with subsequent operations if there is data:

    Optional<User> optional = goodInfos.stream().max(userComparator);

if(optional ! = null && optional.isPresent()) {

    recentUserServer = optional.get().getServer();

}

Copy the code

Pit 2

  • Why didn’t the filter work?

After calling filter, it returns a value, so you need to use a new collection to receive it

.

Then fill the hole slowly