List<String>>ans=newHashMap<>();for(String str:list){List<String>sub=ans.get(str.length());if(sub==null){sub=newArrayList<>();ans.put(str.length(),sub);}sub.add(str);}System.out.println(ans);
其中`Maps`类的`uniqueIndex()`方法可以将List转换为Map。虽然依赖于外部类库,但Guava提供了更多的集合相关功能和效率优化。 Map<String, Entity> map =Maps.uniqueIndex(list, Entity::getKey); 总结: 在List转Map的过程中,我们可以选择使用for循环遍历、Java8 Stream API、Apache Commons Collections或Google Guava...
一、List<Object>转Map<String,String> 二、List<Object>转Map<String,Object>(返回对象本身) 三、List<Object1>转Map<String,Object2>(返回另一个对象) 四、List<Object>转Map<String,List<Object>>(分组)【以1个字段分/以多个字段分】 基础代码: 首先创建两个实体类 @DatapublicclassStudent{//学号private...
public static void main(String[] args) throws Exception { List<String> names = Lists.newArrayList("Answer", "AnswerAIL", "AI"); Map<String, Integer> map = names.stream().collect(Collectors.toMap(v -> v, v -> 1)); System.out.println(map); } } 1. 2. 3. 4. 5. 6. 7. ...
我们在List转Map有三种情况,首先说第一种,最简单、简介的一种 第一种 Map<String, User> maps2 = list.stream().collect (Collectors.toMap(User::getName, Function.identity())); 输出结果 {wangHao=User{name='wangHao', age=20}, piKaQiu=User{name='piKaQiu', age=15}, ...
public static String MapToString(Map, ?> map) { StringBuffer sb = new StringBuffer(); // 遍历map for (Object obj : map.keySet()) { if (obj == null) { continue; } Object key = obj; Object value = map.get(key); if (value instanceof List>) { ...
原因是声明List集合时有的值为空(如图),但是HashMap中k,v是可以存null值的。 解决方法:在转换流中加上判空,即便value为空,依旧输出。(与上面方法三相同) 代码语言:javascript 代码运行次数:0 运行 AI代码解释 Map<String,List<String>>map=list.stream().collect(Collectors.toMap(Person::getId,p->{List<St...
) public Map<Long, String> getIdNameMap(List<Account> accounts) { return accounts.stream()...
在实际项目中我们经常会用到 List 转 Map 操作,在过去我们可能使用的是 for 循环遍历的方式。举个例子:先定义类: // 简单对象 @Accessors(chain = true) // 链式方法 @lombok.Data class User { private String…
利用Stream API的map方法,将原始List转换为所需的Map<String, Map<String, List<Object>>结构。具体步骤如下:使用Stream API对List进行流式操作,对每个元素执行映射操作,创建包含子Map的Map。在这个操作中,元素将作为外部Map的键,同时,将元素的属性(或某些属性)作为子Map的键,并将它们转换为Li...