java - 如何将List转换为Map并使Map成为对象属性的关键

标签 java spring-boot

如果我有一个类事务:

public class Transaction {
    @Id
    @Column(name = "id")
    private Long id;
    
    private String customerName;
    
    private String phoneNumber;
    
    //...getters and setters
    
    }

我通过 Spring Repository 按 customerName 查找交易:

    List<Transaction> findByCustomerName(String customerName);

然后,我想使用以下代码将事务列表转换为映射,但不是使用特定值,有没有办法使映射的键成为对象属性?

Map<Long, Transaction> transactionMap = transactionList.stream()
         .collect(Collectors.toMap(Transaction::getId, Function.identity()));

因此,在 Transaction::getId 中,我只希望它是字符串属性“Id”,而不是该 Transaction 对象的特定 id,但我希望它是列表中的任何属性。 .因此交易的下一个属性将是 customerName,因此它不会显示“Id”,而应显示“customerName”

最佳答案

我不确定您想要的内容如下所示,我假设类 Transaction 中有一个默认构造函数及其字段。

代码片段

Transaction t1 = new Transaction(10L, "AAA", "0987654321");
Transaction t2 = new Transaction(20L, "BBB", "0901234567");

List<Transaction> transactionList = new ArrayList<>();
transactionList.add(t1);
transactionList.add(t2);

// Use id as the key
Map<Long, Transaction> transactionMap1 = transactionList.stream()
         .collect(Collectors.toMap(Transaction::getId, Function.identity()));
System.out.println(transactionMap1.toString());

// Use customerName as the key
Map<String, Transaction> transactionMap2 = transactionList.stream()
         .collect(Collectors.toMap(Transaction::getCustomerName, Function.identity()));
System.out.println(transactionMap2.toString());

控制台输出

{20=Transaction [id=20, customerName=BBB, phoneNumber=0901234567], 10=Transaction [id=10, customerName=AAA, phoneNumber=0987654321]}
{AAA=Transaction [id=10, customerName=AAA, phoneNumber=0987654321], BBB=Transaction [id=20, customerName=BBB, phoneNumber=0901234567]}

关于java - 如何将List转换为Map并使Map成为对象属性的关键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925108/

相关文章:

Spring Boot war 文件适用于嵌入式但不适用于独立的 Tomcat

java - 仅从表中选择某些列

java - Android 自定义 View 只调用 onDraw 一次

java - Collections 类中的方法没有对输入集合进行空检查

java - java中的通用日期解析

mysql - 使用 docker compose 的 Spring Boot mysql 应用程序问题

java - Spring-Boot:使用 Redis 作为 Session Store 时出现异常

java - 如何在 Spring Boot 中为每个用户设置速率限制?

java - pdfptable 中的新行

java - 使用线程编程的方法