java8使⽤stream把List转为Map,根据key提取值转List
import java.util.ArrayList;java stream
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
public static void main(String[] args) {
List<Map<String, String>> list = new ArrayList<>();
{
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "B");
map.put("age", "C");
list.add(map);
}
{
Map<String, String> map = new HashMap<>();
map.put("id", "1");
map.put("name", "E");
map.put("age", "F");
list.add(map);
}
/
/1.返回结果{"1","B"},{"2","E"}
// Map<String, String> a = list.stream().Map(l -> l.get("id"), l -> l.get("name")));
//2.两种⽅法返回结果{"1":{"name":"B","id":"1","age":"C"},"2":{"name":"E","id":"2","age":"F"}}
// Map<String, Map> b = list.stream().Map(l -> l.get("id"), map -> map));
// Map<String, Map> c = list.stream().Map(l -> l.get("id"), Function.identity()));
//3.重复key情况下处理⽅式返回结果{"1":{"name":"E","id":"1","age":"F"}}
// Map<String, Map> d = list.stream().Map(l -> l.get("id"), Function.identity(), (key1, key2) -> key2));
//4.重复key情况下指定返回数据类型处理⽅式返回结果{"1":{"name":"E","id":"1","age":"F"}}
// Map<String, Map> e = list.stream().Map(l -> l.get("id"), Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
/
/5.list根据key合并并转map;返回结果{"1":[{"name":"B","id":"1","age":"C"},{"name":"E","id":"1","age":"F"}]}
// Map<String, List<Map>> lableGbType = list.stream().upingBy(l -> (String) l.get("id")));
//6.根据key提取list中指定的值转List数组;返回结果["1","1"]
// List<String> ids = list.stream().map(m -> (String) m.get("id")).List());
//7.数组去重并转list
/* String[] str = "1,1,2,3,4,5,".split(",");
List<String> listNames = Arrays.stream(str).filter(name -> !isEmpty(name)).distinct().List());*/
}
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论