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

时间:2019-11-19 00:51:15

标签: java spring-boot

如果我的交易类别为:

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<Long, Transaction> transactionMap = transactionList.stream()
         .collect(Collectors.toMap(Transaction::getId, Function.identity()));

因此,我只希望它成为字符串属性“ Id”,而不是该T​​ransaction对象的特定ID,但我希望它成为列表中的任何属性。 。因此,Transaction的下一个属性将是customerName,因此它不会显示“ Id”,而应显示“ customerName”

1 个答案:

答案 0 :(得分:0)

我不确定您想要的显示如下,我假设类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 =交易[id = 20,customerName = BBB,电话号码= 0901234567],10 =交易[id = 10,customerName = AAA,电话号码= 0987654321]}
  {AAA =交易[id = 10,customerName = AAA,电话号码= 0987654321],BBB =交易[id = 20,customerName = BBB,电话号码= 0901234567]}