List<String> list = Arrays.asList("banana","apple","orange");
Map<Integer,List<String>> groups = new HashMap<>();
for (String s:list){
int length = s.length();
if (!groups.containsKey(length)){
groups.put(length,new ArrayList<>());
}
groups.get(length).add(s);
}
System.out.println(groups);
//使用Lambda表达式
Map<Integer,List<String>> groups2 = list.stream().collect(Collectors.groupingBy(String::length));
System.out.println(groups2);
使用Lambda表达式进行分组
最新推荐文章于 2024-02-29 14:07:17 发布