java lambda表达式训练题一

本文介绍了如何在Java8中使用Lambda表达式,包括log4j2配置简化和JUnit5与Lombok的引入。通过实际的交易员和交易类,展示了如何运用Lambda解决一系列查询问题,如过滤、排序和统计交易数据。
摘要由CSDN通过智能技术生成

一、概述

Lambda 表达式,也可称为闭包,它是推动 Java 8 发布的最重要新特性。
Lambda 允许把函数作为一个方法的参数(函数作为参数传递进方法中)。
使用 Lambda 表达式可以使代码变的更加简洁紧凑。

二、准备

1. 引入log4j2

简化版log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<configuration status="off" monitorInterval="0">
	<appenders>
		<console name="Console" target="system_out">
			<patternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
		</console>
	</appenders>
	<loggers>
		<root level="INFO">
			<appender-ref ref="Console" />
		</root>
	</loggers>
</configuration>

2. pom引入junit5、lombok

		<dependency>
			<groupId>org.junit.jupiter</groupId>
			<artifactId>junit-jupiter-api</artifactId>
			<version>5.5.2</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.12</version>
			<scope>provided</scope>
		</dependency>

三、训练题


import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LambdaTest
{
    private static List<Transaction> transactions = new ArrayList<>();
    
    @BeforeAll
    public static void init()
    {
        Trader raoul = new Trader("Raoul", "Cambridge");
        Trader mario = new Trader("Mario", "Milan");
        Trader alan = new Trader("Alan", "Cambridge");
        Trader brian = new Trader("Brian", "Cambridge");
        
        transactions.add(new Transaction(brian, 2011, 300));
        transactions.add(new Transaction(raoul, 2012, 1000));
        transactions.add(new Transaction(raoul, 2011, 400));
        transactions.add(new Transaction(mario, 2012, 710));
        transactions.add(new Transaction(mario, 2012, 700));
        transactions.add(new Transaction(alan, 2012, 950));
        log.info("★★★★★★★★ @BeforeAll");
    }
    
    @Test
    public void test()
    {
        // 现需要使用lambda表达式实现如下功能:
        // (1) 找出2011年发生的所有交易,并按交易额排序(从低到高)
        // (2) 交易员都在哪些不同的城市工作过?
        // (3) 查找所有来自于剑桥的交易员,并按姓名排序
        // (4) 返回所有交易员的姓名字符串,按字母顺序排序
        // (5) 有没有交易员是在米兰工作的?
        // (6) 打印生活在剑桥的交易员的所有交易额
        // (7) 所有交易中,最高的交易额是多少?
        // (8) 找到交易额最小的交易
    }
}

/**
 * 交易员
 */
@Data
class Trader
{
    private final String name;
    
    private final String city;
    
    /**
     * @param name 姓名
     * @param city 城市
     */
    public Trader(String name, String city)
    {
        this.name = name;
        this.city = city;
    }
}

/**
 * 交易
 */
@Data
class Transaction
{
    private final Trader trader;
    
    private final int year;
    
    private final int value;
    
    /**
     * @param trader 交易员
     * @param year 年份
     * @param value 交易额
     */
    public Transaction(Trader trader, int year, int value)
    {
        this.trader = trader;
        this.year = year;
        this.value = value;
    }
}

四、参考答案

注意:不一定是最优解

    @Test
    public void test01()
    {
        log.info("找出2011年发生的所有交易,并按交易额排序(从低到高)");
        transactions.stream()
            .filter(t -> t.getYear() == 2011) // 2011年
            .sorted(Comparator.comparing(Transaction::getValue))// 排序
            .forEach(t -> log.info("{}", t));
        
        transactions.stream()
            .filter(t -> t.getYear() == 2011)// 2011年
            .sorted(Comparator.comparingInt(Transaction::getValue)) // 排序
            .forEach(t -> log.info("{}", t));
    }
    
    @Test
    public void test02()
    {
        log.info("交易员都在哪些不同的城市工作过?");
        transactions.stream()
            .map(t -> t.getTrader().getCity()) // 城市
            .distinct() // 去重
            .forEach(log::info);
        
        transactions.stream()
            .map(t -> t.getTrader().getCity()) // 城市
            .distinct() // 去重
            .collect(Collectors.toList())// 收集
            .forEach(log::info);
    }
    
    @Test
    public void test03()
    {
        log.info("查找所有来自于剑桥的交易员,并按姓名排序");
        transactions.stream()
            .filter(t -> t.getTrader().getCity().equals("Cambridge"))// 剑桥
            .map(Transaction::getTrader) // 交易员
            .distinct() // 去重
            .sorted(Comparator.comparing(Trader::getName)) // 排序
            .forEach(t -> log.info("{}", t));
        
        transactions.stream()
            .filter(t -> t.getTrader().getCity().equals("Cambridge"))// 剑桥
            .map(Transaction::getTrader) // 交易员
            .distinct() // 去重
            .sorted(Comparator.comparing(Trader::getName)) // 排序
            .collect(Collectors.toList())// 收集
            .forEach(t -> log.info("{}", t));
    }
    
    @Test
    public void test04()
    {
        log.info("返回所有交易员的姓名字符串,按字母顺序排序");
        transactions.stream()
            .map(t -> t.getTrader().getName()) // 交易员名字
            .distinct() // 去重
            .sorted() // 排序
            .forEach(log::info);
        
        transactions.stream()
            .map(Transaction::getTrader) // 交易
            .collect(Collectors.toList())// 收集
            .stream()
            .map(Trader::getName) // 交易员名字
            .distinct() // 去重
            .sorted() // 排序
            .forEach(log::info);
    }
    
    @Test
    public void test05()
    {
        log.info("有没有交易员是在米兰工作的?");
        log.info("{}", transactions.stream().anyMatch(t -> t.getTrader().getCity().equals("Milan")));
    }
    
    @Test
    public void test06()
    {
        log.info("打印生活在剑桥的交易员的所有交易额之和");
        int total = transactions.stream()
            .filter(t -> t.getTrader().getCity().equals("Cambridge")) // 剑桥
            .mapToInt(Transaction::getValue) // 交易额
            .sum();
        log.info("{}", total);
    }
    
    @Test
    public void test07()
    {
        log.info("有交易中,最高的交易额是多少?");
        int max = transactions.stream()
            .mapToInt(Transaction::getValue) // 取交易额
            .max() // 最高
            .getAsInt();
        log.info("{}", max);
        
        int max2 = transactions.stream()
            .max(Comparator.comparingInt(Transaction::getValue)) // 最高交易额
            .get() // 获取对象
            .getValue();
        log.info("{}", max2);
    }
    
    @Test
    public void test08()
    {
        log.info("找到交易额最小的交易");
        Transaction min = transactions.stream().min(Comparator.comparing(Transaction::getValue)).get();
        log.info("{}", min);
    }

有任何问题和建议,都可以向我提问讨论,大家一起进步,谢谢!

-over-

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值