由于水平原因,博客大部分内容摘抄于网络,如有错误或者侵权请指出,本人将尽快修改

lambda必须要会的十种姿势

  • flatmap 的使用

处理嵌套,一般是二维数组(集合)

import java.util.*;
import java.util.stream.*;

class Book {
    private List<Chapter> chapters;

    public Book(List<Chapter> chapters) {
        this.chapters = chapters;
    }

    public List<Chapter> getChapters() {
        return chapters;
    }
}

class Chapter {
    private List<String> paragraphs;

    public Chapter(List<String> paragraphs) {
        this.paragraphs = paragraphs;
    }

    public List<String> getParagraphs() {
        return paragraphs;
    }
}

public class FlatMapExample {
    public static void main(String[] args) {
        List<Book> books = Arrays.asList(
                new Book(Arrays.asList(
                        new Chapter(Arrays.asList("Paragraph 1.1", "Paragraph 1.2")),
                        new Chapter(Arrays.asList("Paragraph 1.3"))
                )),
                new Book(Arrays.asList(
                        new Chapter(Arrays.asList("Paragraph 2.1")),
                        new Chapter(Arrays.asList("Paragraph 2.2", "Paragraph 2.3"))
                ))
        );

        List<String> allParagraphs = books.stream()
                .flatMap(book -> book.getChapters().stream())
                .flatMap(chapter -> chapter.getParagraphs().stream())
                .collect(Collectors.toList());

        System.out.println(allParagraphs);
    }
}

嵌套List

List<List<String>> list = dogetXidsForTargetMap(stringLongMap, start, end, pageSize);
List<String> xids = list.stream().flatMap(Collection::stream).collect(Collectors.toList());
  • map和reduce
import java.util.Arrays;
import java.util.List;

class SumAndProduct {
    private int sum;
    private int product;

    public SumAndProduct(int sum, int product) {
        this.sum = sum;
        this.product = product;
    }

    public SumAndProduct add(int value) {
        return new SumAndProduct(this.sum + value, this.product * value);
    }

    public SumAndProduct combine(SumAndProduct other) {
        return new SumAndProduct(this.sum + other.sum, this.product * other.product);
    }

    @Override
    public String toString() {
        return "Sum: " + sum + ", Product: " + product;
    }
}

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

        SumAndProduct result = numbers.stream()
                .reduce(
                        new SumAndProduct(0, 1),         // 初始值
                        (partialResult, number) -> partialResult.add(number), // 累加器
                        SumAndProduct::combine           // 组合器
                );

        System.out.println(result);
    }
}
  • suplier
loginService.checkLogin(LoginType.PASSWORD, tenantId, username, () -> !BCrypt.checkpw(password, loginUser.getPassword()));

    /**
     * 登录校验
     */
    public void checkLogin(LoginType loginType, String tenantId, String username, Supplier<Boolean> supplier) {
        String errorKey = GlobalConstants.PWD_ERR_CNT_KEY + username;
        String loginFail = Constants.LOGIN_FAIL;
        Integer maxRetryCount = userPasswordProperties.getMaxRetryCount();
        Integer lockTime = userPasswordProperties.getLockTime();

        // 获取用户登录错误次数,默认为0 (可自定义限制策略 例如: key + username + ip)
        int errorNumber = ObjectUtil.defaultIfNull(RedisUtils.getCacheObject(errorKey), 0);
        // 锁定时间内登录 则踢出
        if (errorNumber >= maxRetryCount) {
            recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
            throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
        }

        if (supplier.get()) {
            // 错误次数递增
            errorNumber++;
            RedisUtils.setCacheObject(errorKey, errorNumber, Duration.ofMinutes(lockTime));
            // 达到规定错误次数 则锁定登录
            if (errorNumber >= maxRetryCount) {
                recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitExceed(), maxRetryCount, lockTime));
                throw new UserException(loginType.getRetryLimitExceed(), maxRetryCount, lockTime);
            } else {
                // 未达到规定错误次数
                recordLogininfor(tenantId, username, loginFail, MessageUtils.message(loginType.getRetryLimitCount(), errorNumber));
                throw new UserException(loginType.getRetryLimitCount(), errorNumber);
            }
        }

        // 登录成功 清空错误次数
        RedisUtils.deleteObject(errorKey);
    }
  • consumer
RedisUtils.publish(key, value, consumer -> {
            System.out.println("发布通道 => " + key + ", 发送值 => " + value);
        });

/**
     * 发布通道消息
     *
     * @param channelKey 通道key
     * @param msg        发送数据
     * @param consumer   自定义处理
     */
    public static <T> void publish(String channelKey, T msg, Consumer<T> consumer) {
        RTopic topic = CLIENT.getTopic(channelKey);
        topic.publish(msg);
        consumer.accept(msg);
    }

 

posted @ 2024-07-06 17:15  小纸条  阅读(24)  评论(0)    收藏  举报