preface
This article introduces the Stream Stream List and Map interconversion process, and analyzes the problems encountered in the conversion process.
Map to List
1.1 analysis
In default order
mapToList.entrySet().stream().map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
Copy the code
Sort by key
mapToList.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
Copy the code
Sort by key
mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
Copy the code
Sort by key in reverse order
mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
Copy the code
Sort by value
mapToList.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
Copy the code
Sort by value in reverse order
mapToList.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
Copy the code
1.2 Complete Code
Entity class
/ * * *@author lilinchao
* @date 2021/7/28
* @description1.0 * * /
public class User {
private Integer id;
private String name;
public User(a) {}public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId(a) {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString(a) {
return "User{" +
"id=" + id +
", name='" + name + '\' ' +
'} '; }}Copy the code
Map to List code
import java.util.*;
import java.util.stream.Collectors;
/ * * *@author lilinchao
* @date 2021/7/28
* @description1.0 * * /
public class StreamMapToList {
/** * Data initialization */
private static final Map<Integer, String> mapToList;
static
{
mapToList = new HashMap<Integer, String>();
mapToList.put(1003."Thymee");
mapToList.put(1001."Leefs");
mapToList.put(1002."Jeyoo");
}
public static void main(String ages[]){
List<User> userList = defaultOrder();
System.out.println(userList);
List<User> userList2and = orderByKeyMethodOne();
System.out.println(userList2and);
List<User> userList3and = orderByKeyMethodTwo();
System.out.println(userList3and);
List<User> userList4and = reverseOrderByKey();
System.out.println(userList4and);
List<User> userList5and = orderByValue();
System.out.println(userList5and);
List<User> userList6and = reverseOrderByValue();
System.out.println(userList6and);
}
/** ** in the default order */
public static List<User> defaultOrder(a){
List<User> userList = mapToList.entrySet().stream().map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
return userList;
}
/** * sort by key, method 1 */
public static List<User> orderByKeyMethodOne(a){
List<User> userList = mapToList.entrySet().stream().sorted(Comparator.comparing(a -> a.getKey())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/** * sort by key, method 2 */
public static List<User> orderByKeyMethodTwo(a){
List<User> userList = mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey()).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/** * Sort by key */
public static List<User> reverseOrderByKey(a){
List<User> userList = mapToList.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
return userList;
}
/** * sort by value */
public static List<User> orderByValue(a){
List<User> userList = mapToList.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).map(a -> new User(a.getKey(), a.getValue())).collect(Collectors.toList());
return userList;
}
/** * Sort by value in reverse order */
public static List<User> reverseOrderByValue(a){
List<User> userList = mapToList.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue())).map(a -> new User(a.getKey(),a.getValue())).collect(Collectors.toList());
returnuserList; }}Copy the code
The results
[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}, User{id=1003, name='Thymee'}]
[User{id=1003, name='Thymee'}, User{id=1002, name='Jeyoo'}, User{id=1001, name='Leefs'}]
[User{id=1002, name='Jeyoo'}, User{id=1001, name='Leefs'}, User{id=1003, name='Thymee'}]
[User{id=1003, name='Thymee'}, User{id=1001, name='Leefs'}, User{id=1002, name='Jeyoo'}]
Copy the code
List to Map
2.1 analysis
Specify key-value, where value is the value of an attribute in the object
userList.stream().collect(Collectors.toMap(User::getId, User::getName));
Copy the code
Specify key-value, where value is the object itself
User->User is a lambda expression that returns itself
userList.stream().collect(Collectors.toMap(User::getId, User->User));
Copy the code
Specify key-value, where value is the object itself
Function.identity() is shorthand and returns the object itself
userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Copy the code
Specify key-value, the resolution of key conflicts
(key1,key2)->key2: the second key overwrites the first key (key1,key2)->key1: preserves the first key
userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
Copy the code
2.2 Complete Code
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/ * * *@author lilinchao
* @date 2021/7/28
* @description1.0 * * /
public class StreamListToMap {
private static final List<User> userList;
static
{
userList = Arrays.asList(
new User(1003."keko"),
new User(1001."jeek"),
new User(1002."mack")); }public static void main(String ages[]){
Map<Integer, String> map = method01();
System.out.println(map);
Map<Integer, User> map2and = method02();
System.out.println(map2and);
Map<Integer, User> map3and = method03();
System.out.println(map3and);
Map<Integer, User> map4and = method04();
System.out.println(map4and);
}
/** * specifies key-value, which is the value of an attribute in the object */
public static Map<Integer,String> method01(a){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName));
return userMap;
}
/** * specifies key-value, where value is the object itself and User->User is a lambda expression that returns itself */
public static Map<Integer,User> method02(a){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, User->User));
return userMap;
}
Function. Identity () returns the object itself */
public static Map<Integer,User> method03(a){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
return userMap;
}
* (key1,key2)->key2: the second key overwrites the first key * (key1,key2)->key1: preserves the first key */
public static Map<Integer,User> method04(a){
Map<Integer, User> userMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(),(key1,key2)->key2));
returnuserMap; }}Copy the code
The results
{1001=jeek, 1002=mack, 1003=keko}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}
{1001=User{id=1001, name='jeek'}, 1002=User{id=1002, name='mack'}, 1003=User{id=1003, name='keko'}}
Copy the code
3. Common problems with converting a List to a Map
3.1 Common Problems
Problem a
Error Duplicate key XXXX
This problem is caused by duplicate key values during Map collection generation
The solution
1. The following value overwrites the preceding value
userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key2));
Copy the code
Or you can keep the previous value and replace key2 with key1
2. Value Is spliced
userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key1+","+key2));
Copy the code
3. If the key is repeated, the collection is returned
userList2and.stream().collect(Collectors.toMap(User::getId, p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
returnvalue1; }));Copy the code
Question 2
Error: the Exception in the thread “is the main” Java. Lang. NullPointerException
The problem is that the value is null when the Map collection is stored
The solution
Nulls are added to the conversion stream, even if value is null. (Same as method 3 above)
3.2 Complete Code
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/ * * *@author lilinchao
* @date 2021/7/28
* @description1.0 * * /
public class StreamListToMapAnalyze {
private static final List<User> userList;
private static final List<User> userList2and;
static
{
// Duplicate key
userList = Arrays.asList(
new User(1003."keko"),
new User(1001."jeek"),
new User(1001."teek"),
new User(1002."mack"));// Duplicate key,value is null
userList2and = Arrays.asList(
new User(1003."keko"),
new User(1001."jeek"),
new User(1001."teek"),
new User(1002.null)); }public static void main(String ages[]){
Map<Integer, String> map = keyRepeatMethod01();
System.out.println(map);
Map<Integer, String> map2and = keyRepeatMethod02();
System.out.println(map2and);
Map<Integer,List<String>> map3and = keyRepeatMethod03();
System.out.println(map3and);
}
/** * if the key is repeated, the following value overwrites the preceding value */
public static Map<Integer,String> keyRepeatMethod01(a){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key2));
return userMap;
}
/** * when key is repeated, value is concatenated */
public static Map<Integer,String> keyRepeatMethod02(a){
Map<Integer, String> userMap = userList.stream().collect(Collectors.toMap(User::getId, User::getName, (key1, key2) -> key1+","+key2));
return userMap;
}
/** * key returns null value when the key is repeated. Null value is added to the conversion stream
public static Map<Integer,List<String>> keyRepeatMethod03(){
Map<Integer, List<String>> userListMap = userList2and.stream().collect(Collectors.toMap(User::getId, p -> {
List<String> getNameList = new ArrayList<>();
getNameList.add(p.getName());
return getNameList;
},
(List<String> value1, List<String> value2) -> {
value1.addAll(value2);
returnvalue1; }));returnuserListMap; }}Copy the code
The results
{1001=teek, 1002=mack, 1003=keko}
{1001=jeek,teek, 1002=mack, 1003=keko}
{1001=[jeek, teek], 1002=[null], 1003=[keko]}
Copy the code
Attached: Reference article links
www.cnblogs.com/fugitive/p/…
www.jb51.net/article/170…