[英]How to convert List to Map and make the map key the object's attributes
如果我有一個 class 交易:
public class Transaction { @Id @Column(name = "id") private Long id; private String customerName; private String phoneNumber; //...getters and setters }
我通過 Spring 存儲庫找到了 customerName 的交易:
List<Transaction> findByCustomerName(String customerName);
然后我想使用以下代碼將事務列表轉換為 map,但不是特定值,有沒有辦法使地圖的鍵成為 object 屬性?
Map<Long, Transaction> transactionMap = transactionList.stream().collect(Collectors.toMap(Transaction::getId, Function.identity()));
因此,在 Transaction::getId 處,不是該事務 object 的特定 id,我只希望它是字符串屬性“Id”,但我希望它是列表中的任何屬性......所以Transaction 的下一個屬性是 customerName,所以它不會顯示“Id”它應該顯示“customerName”
我不確定您想要的內容如下所示,我假設 class 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());
控制台 output
{20=交易 [id=20, customerName=BBB, phoneNumber=0901234567], 10=交易 [id=10, customerName=AAA, phoneNumber=0987654321]}
{AAA=交易 [id=10, customerName=AAA, phoneNumber=0987654321], BBB=交易 [id=20, customerName=BBB, phoneNumber=0901234567]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.