对一个 List 里面相同属性的内容进行分类,如:对相同部门的员工进行分类。
思路是使可以区分类型的属性进行分类,以部门类型为例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| List<Devloper> devlopers = new ArrayList<>(); devlopers.add(new Devloper(1, "嗯哼", 1)); devlopers.add(new Devloper(2, "啊哈", 1)); devlopers.add(new Devloper(3, "哦吼", 1)); devlopers.add(new Devloper(4, "呃呵", 2)); devlopers.add(new Devloper(5, "呜唿", 2));
Map<Integer, List<Devloper>> devloperMap = new HashMap<>(); for (Devloper devloper: devlopers) { if (devloperMap.containsKey(devloper.getDept())) { devloperMap.get(devloper.getDept()).add(devloper); } else { List<Devloper> devs = new ArrayList<>(); devs.add(devloper); devloperMap.put(devloper.getDept(), devs); } }
|
结果:
1 2 3 4 5 6 7 8 9 10 11
| { 1=[ Devloper{id=1, name='嗯哼', dept=1}, Devloper{id=2, name='啊哈', dept=1}, Devloper{id=3, name='哦吼', dept=1} ], 2=[ Devloper{id=4, name='呃呵', dept=2}, Devloper{id=5, name='呜唿', dept=2} ] }
|