1 List to Map
@Getter
@Setter
public class User {
private Long id;
private String name;
public User(Long id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
package com.mervyn.filterdemo;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
List<User> names = new ArrayList<>();
names.add(new User(1L,"郭雨桐"));
names.add(new User(2L,"尚书雨"));
names.add(new User(3L,"李雪晴"));
names.add(new User(4L,"刘小晓"));
Map<Long, User> userMap = names.stream().collect(Collectors.toMap(User::getId, user -> user));
}
}
2 Map to List
package com.mervyn.filterdemo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Test {
public static void main(String[] args) {
Map<Long, String> userMap = new HashMap<>();
userMap.put(1L, "郭雨桐");
userMap.put(2L, "尚书雨");
userMap.put(3L, "李雪晴");
userMap.put(4L, "刘小晓");
// 将Map的value值转成list
List<String> usernames = userMap.values().stream().collect(Collectors.toList());
// 将Map的key值转成list
List<Long> userIds = userMap.keySet().stream().collect(Collectors.toList());
}
}
网友评论