java 8 list Collectors.toMap 保持顺序的两种方案
1 年前
· 来自专栏
java技术
Java 8 list 转 map 保持顺序
思路直接转换为LinkedHashMap。
User user = new User();
user.setAccountId("1");
List<User> users = Lists.newArrayList();
User user2 = new User();
user2.setAccountId("2");
User user3 = new User();
user3.setAccountId("3");
User user4 = new User();
user4.setAccountId("4");
users.add(user);
users.add(user3);
users.add(user2);
users.add(user4);
常用的两个参数方法
public static <T, K, U>
Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper) {
return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
}
Map<String, User> userMap2 = Future home of users.stream().collect(Collectors.toMap(a -> a.getAccountId(), a -> a));
log.info("转回map:{}", JSON.toJSONString(userMap2));
//转回map:{"1":{"account_id":"1","query":{}},"2":{"account_id":"2","query":{}},"3":{"account_id":"3","query":{}},"4":{"account_id":"4","query":{}}}
这个函数是转map,无法保证数据的顺序。而保留数据的顺序实际上就转为 LinkedHashMap
四个参数方法
public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction,
Supplier<M> mapSupplier) {
BiConsumer<M, T> accumulator
= (map, element) -> map.merge(keyMapper.apply(element),
valueMapper.apply(element), mergeFunction);
return new CollectorImpl<>(mapSupplier, accumulator, mapMerger(mergeFunction), CH_ID);