使用创建对像,使用for循环。
google提供的guava包
List<User> list = new ArrayList<>();
list.add(new User(1L,"link"));
list.add(new User(2L,"wangw"));
list.add(new User(3L,"wangl"));
Map<Long,User> maps = Maps.uniqueIndex(list.iterator(), new Function<User, Long>() {
@Override
public Long apply(User user){
return user.getId();
}
});
//{1=User{id=1, name='link'}, 2=User{id=2, name='wangw'}, 3=User{id=3, name='wangl'}}
System.out.println(maps);
return maps;
2.使用 Maps.asMap接口,与 uniqueIndex 相反,将返回值作为value
Set<User> set = new HashSet<>();
set.add(new User(1L,"link"));
set.add(new User(2L,"wangw"));
set.add(new User(3L,"wangl"));
Map<User,Long> longUserMap = Maps.asMap(set, new Function<User, Long>() {
@Nullable
@Override
public Long apply(@Nullable User input) {
return input.getId();
}
});
//{User{id=3, name='wangl'}=3, User{id=2, name='wangw'}=2, User{id=1, name='link'}=1}
System.out.println(longUserMap);
return longUserMap;
public static Map<Long,String> listToMapOne(List<Supplier> suppliers){
Map<Long,String> map = suppliers.stream().collect(Collectors.toMap(Supplier::getId, Supplier::getName));
return map;
}
Map<Long,Supplier> map = suppliers.stream()
.collect(Collectors.toMap(Supplier::getId,supplier -> supplier));
return map;
Map<Long,Supplier> map = suppliers.stream()
.collect(Collectors.toMap(Supplier::getId, Function.identity()));
return map;
Map<Long,Supplier> map = suppliers.stream().collect(
Collectors.toMap(Supplier::getId,Function.identity(),(k1,k2)->k2));
return map;
LinkedHashMap<Long,Supplier> map = suppliers.stream().collect(
Collectors.toMap(Supplier::getId,Function.identity(),
(k1,k2) -> k2,LinkedHashMap::new));
return map;