Work experience|I have recorded 10 common combat operations used by lambada to process collections

Follow the official account "AI Coder" to receive a copy of the latest interview materials for 2021, and reply to the "source code" in the official account to obtain the source code of this project

Recently, I often use lambada expressions on projects, but I can’t remember it. I’ve always been on Baidu. I forgot after writing it. It feels very time-consuming; this time I’ll take some time to deal with some commonly used lambada examples of collections. They are all saved (de-duplication, grouping, summation, list to map, etc.), so you don’t need to search everywhere in the future, you can just share them with your classmates; in addition, I will also give you some pitfalls encountered when using lambada Share it with everyone, all the codes are ready to use! ! ! This document is continuously updated...

Example demonstration

Commodity entity

@Data
@AllArgsConstructor
public class GoodInfo {
    private String mallSource;
    private String skuNo;
    private int price;
    private int monthCount;
}

Sort

The frequency of collection sorting in projects is quite high, here is an example of sorting by sales

   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));

    // 按照销量正序 从小到大排序
    goodInfos.sort(Comparator.comparing(GoodInfo::getMonthCount));
    // 按照销量倒序 从大到小排序
    goodInfos.sort(Comparator.comparing(GoodInfo::getMonthCount).reversed());

Take the maximum value/take the minimum value/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));

    // 获取最大销量  注意如果求最大值是在filter之后使用例如,goodInfos.stream().filter().max一定要判断filter后集合数量是否不为空,否则使用max的get方法会报错
    GoodInfo hotGoodInfo = goodInfos.stream().max(Comparator.comparing(GoodInfo::getMonthCount)).get();
    // 求最低价格商品
    GoodInfo lowPriceGoodInfo = goodInfos.stream().min(Comparator.comparing(GoodInfo::getMonthCount)).get();
    // 计算商品总价格
    int sum = goodInfos.stream().mapToInt(person -> person.getPrice()).sum();
    // 求平均价格
    double avg = goodInfos.stream().mapToInt(person -> person.getPrice()).average().getAsDouble();

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));

    // 遍历输出所有商品id
    goodInfos.forEach(
        goodInfo -> {
          System.out.println(goodInfo.getSkuNo());
        });

Entity collection to single attribute collection

Often in our projects there will be such a requirement: I need to extract a certain attribute in the collection, and then assemble it into a collection. The usual practice is to create a string collection first, then traverse the original collection, take out the data, and put it in the string collection. Although it can also achieve the function, it is too cumbersome. Now it can be done with a line of lambada expression:

    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));

    // 将list转为某个属性map 这里是把所有skuno全部取出来 作为集合
    List<String> skuNos = goodInfos.stream().map(goodInfo -> goodInfo.getSkuNo()).collect(Collectors.toList());

Entity collection to map return

    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));

    // 将list转为map,key 为商品id
    Map<String, GoodInfo> map = goodInfos.stream().collect(Collectors.toMap(GoodInfo::getSkuNo, goodInfo -> goodInfo));

Entity collections are grouped according to a certain 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));

    // 按照商品来源分组
    Map<String, List<GoodInfo>> map = goodInfos.stream().collect(Collectors.groupingBy(GoodInfo::getMallSource));

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));

    // 过滤商品价格大于300的
    // todo 过滤后一定要使用集合接收,否则等于没有过滤

    List<GoodInfo> collect =
        goodInfos.stream()
            .filter(goodInfo -> goodInfo.getPrice() > 300)
            .collect(Collectors.toList());
    collect.forEach(
        goodInfo -> {
          System.out.println(goodInfo.getPrice());
        });

Deduplication (two methods are optional)

Method one set to remove duplicates

    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));

    // 使用treeset 集合来实现去重,这里一定要使用集合接收,不然等于没有去重
    List<GoodInfo> goodInfos1 =
        goodInfos.stream()
            .collect(
                Collectors.collectingAndThen(
                    Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(o -> o.getSkuNo()))),
                    ArrayList::new));

Method two map de-duplication

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));

    // 使用map去重
    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;
  }

Pits encountered

Pit one

  • Error message:
    java.util.NoSuchElementException: No value present

  • Solution:
    Generally, this error occurs when operations such as max/min are used after the filter operation, and then the get method is called, and the data cannot be retrieved, which results in an error. Therefore, it is recommended to check that there is data after the filter operation, and then proceed when there is data. Follow-up operations:

    Optional<User> optional = goodInfos.stream().max(userComparator);
if(optional != null && optional.isPresent()) {
    recentUserServer = optional.get().getServer();
}

Pit two

  • Why doesn't the filter work?

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

。。。

Fill the hole slowly in the follow-up

Guess you like

Origin blog.csdn.net/weixin_34311210/article/details/113577012