如果我有一个类事务:
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/