相信很多开发的小伙伴都有遇到过需要对表按特定条件进行查询,然后再进行归类,比如:对员工表进行检索,然后分别按他们所在的部门进行归类,一般的做法都是按部门唯一标识(比如部门编号、部门名称等)进行一次一次查询,这样做的缺点显而易见,会造成与数据库的多次连接,从而影响效率和性能。而我的做法是直接对员工表进行一次全部读取,然后在本地根据条件再进行归类,这就涉及到需要对List进行处理,将父List直接拆分成多个子List。当然,上面举的例子只是最简单的业务场景,实际场景可能错综复杂,但
话不多说,直接上代码。当然,上面举的例子只是最简单的业务场景,实际场景可能错综复杂,但我下面提供参考的这段代码已经够用了。
package com.ruoyi.web.test; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; public class DealList { /** * 按照List<Map<String,Object>>里面map的某个value重新封装成多个不同的list, 原始数据类型List<Map * <String,Object>>, 转换后数据类型Map<String,List<Map<String,Object>>> * * @param list * @param oneMapKey * @return */ private static List<Map<String, Object>> change(List<Map<String, Object>> inList, String oneMapKey, List<Map<String, Object>> outList) { // 1.将某个key的值存在set中 Set<Object> setTmp = new HashSet<Object>(); for (Map<String, Object> tmp : inList) { setTmp.add(tmp.get(oneMapKey)); } // 2.遍历set Iterator<Object> it = setTmp.iterator(); while (it.hasNext()) { String oneMapValueStr = ""; String oneSetTmpStr = (String) it.next(); Map<String, Object> oneSetTmpMap = new HashMap<String, Object>(); List<Map<String, Object>> oneSetTmpList = new ArrayList<Map<String, Object>>(); for (Map<String, Object> tmp : inList) { oneMapValueStr = (String) tmp.get(oneMapKey); if (oneSetTmpStr.equals(oneMapValueStr)) { oneSetTmpMap.put("text", oneSetTmpStr); oneSetTmpList.add(tmp); } } oneSetTmpMap.put("array", oneSetTmpList); outList.add(oneSetTmpMap); } return outList; } public static void main(String[] args) { Map<String, Object> map1 = new HashMap<String, Object>(); Map<String, Object> map2 = new HashMap<String, Object>(); Map<String, Object> map3 = new HashMap<String, Object>(); Map<String, Object> map4 = new HashMap<String, Object>(); List<Map<String, Object>> inList = new ArrayList<Map<String, Object>>(); map1.put("dept", "开发部"); map1.put("name", "张三"); map2.put("dept", "业务部"); map2.put("name", "李华"); map3.put("dept", "开发部"); map3.put("name", "李四"); map4.put("dept", "业务部"); map4.put("name", "王明"); inList.add(map1); inList.add(map2); inList.add(map3); inList.add(map4); System.out.println("原始的List:" + inList); List<Map<String, Object>> outList = new ArrayList<Map<String, Object>>(); outList = change(inList, "dept", outList); System.out.println("处理后的List:" + outList); } }
结果:
原始的List:[{name=张三, dept=开发部}, {name=李华, dept=业务部}, {name=李四, dept=开发部}, {name=王明, dept=业务部}]
处理后的List:[{array=[{name=张三, dept=开发部}, {name=李四, dept=开发部}], text=开发部}, {array=[{name=李华, dept=业务部}, {name=王明, dept=业务部}], text=业务部}]