JDK8中List使用stream转map常用方式

//第一种: 取list中某2个字段作为Map的K,V
public Map<Long, String> getIdNameMap(List<User> users) {
    return accounts.stream().collect(Collectors.toMap(User::getId, User::getUserName));
}

//第二种:将id和实体Bean做为K,V account -> account是一个返回本身的lambda表达式,后面的使用Function接口中的一个默认方法代替,使整个方法更简洁优雅。
方式一:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
方式二:
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Function.identity()));
}

//第三种: key存在重复记录时处理,如果使用第一种方法会出错,所以这里只是简单的使用后者覆盖前者来解决key重复问题
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}

//第四种: 使用某个具体的Map类来保存,如保存时使用LinkedHashMap
public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在Java 8,可以使用Stream流以及Collectors类的toMap方法将List换为Map。一种常见的方式使用Collectors.toMap方法进行换。例如,如果你有一个List<Account>的对象列表,你可以使用以下代码将其换为以账户ID为键,用户名为值的Map: ```java public Map<Long, String> getIdNameMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername)); } ``` 另外,如果你想以某个字段进行分组,并将对象实体本身作为值,你可以设置toMap方法的第二个参数为实体本身。例如,如果你有一个List<Account>的对象列表,并希望以账户ID进行分组,你可以使用以下代码: ```java public Map<Long, Account> getIdAccountMap(List<Account> accounts) { return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account)); } ``` 以上是两种常见的将List换为Map方式使用Java 8的Stream和Collectors类,可以更加简洁和高效地进行这种换操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Java8listmap方法](https://blog.csdn.net/Alecor/article/details/124388252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值