目录
1、使用场景
我们实际开发工作之中可能会遇见很多这种情况,要查询某个分页List,但是里面设计一些字典字段或者其他关联表的名称。在实际实现过程之中最简单粗暴的方法就是返回分页数据之后,循环分页结果如10条记录进行再次查询,假如分页List的记录项之中有很多类似的需要翻译名称势必会多次查询数据库。我在实际实践之中可能针对分页返回的结果,通过Stream的去重distinct处理只后,通过mysql的in查询,这样就可以通过id值和对应的翻译名称值一次返回需要处理的结果对象。然后通过把查询结果转换为Map<Long,String> ==>Map<id,name> 这样就可以在分页List之中通过对应的id值直接获得对应翻译名称值。是不是这样查询次数更少,同时也顺利实现了翻译结果。
2、代码实现
public class Dept {
private Long id;
private String name;
public Dept(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Test
public void ListBeanOrMapToMap() {
List<Map> deptList = new ArrayList();
Map deptMap = new HashMap();
deptMap.put("id", "1");
deptMap.put("name", "新希望集团");
deptList.add(deptMap);
deptMap = new HashMap();
deptMap.put("id", 2);
deptMap.put("name", "四川分公司");
deptList.add(deptMap);
deptMap = new HashMap();
deptMap.put("id", 3);
deptMap.put("name", "山东分公司");
deptList.add(deptMap);
//变量deptList 能后通过get 方法取出数据并给新map 赋值
Map<String, Object> resultDeptMap = deptList.stream().collect(
Collectors.toMap(s -> s.get("id").toString(), s -> s.get("name")));
System.out.println("resultDeptMap==> " + resultDeptMap.toString());
List<Dept> deptBeanList = new ArrayList<>();
deptBeanList.add(new Dept(1L, "新希望集团"));
deptBeanList.add(new Dept(2L, "四川分公司"));
deptBeanList.add(new Dept(3L, "山东分公司"));
Map resultDeptBeanMap = deptBeanList.stream().collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));
System.out.println("resultDeptBeanMap==> " + resultDeptBeanMap.toString());
//解决重复的key问题 此处可能其他name作为key
deptMap = new HashMap();
deptMap.put("id", 2);
deptMap.put("name", "辽宁分公司");
deptList.add(deptMap);
Map<String, Object> duplicatedKeyMap = deptList.stream().collect(
Collectors.toMap(s -> s.get("id").toString(), s -> s.get("name"), (oldValue, newValue) -> oldValue)
);
System.out.println("duplicatedKeyMap: ==> " + duplicatedKeyMap.toString());
}
3、成果展现
resultDeptMap==> {1=新希望集团, 2=四川分公司, 3=山东分公司}
resultDeptBeanMap==> {1=新希望集团, 2=四川分公司, 3=山东分公司}
duplicatedKeyMap: ==> {1=新希望集团, 2=四川分公司, 3=山东分公司}
Process finished with exit code 0
4、总结
我们在实际开发之中可能返回的List<Map>或者List<Bean>,我们为了快速返回结果,需要对List转换为Map,然后通过Key能够很快获得对应翻译的名称值。同时有些环境下可能Key重复的问题需要处理一下。