最近看java8的新特性发现了个好用的功能
根据一个字段进行分组
public class ListGroupBy {
public static void main(String[] args) {
List<Score> scoreList = new ArrayList<>();
scoreList.add(new Score().setStudentId("001").setScoreYear("2018").setScore(100.0));
scoreList.add(new Score().setStudentId("001").setScoreYear("2019").setScore(59.5));
scoreList.add(new Score().setStudentId("001").setScoreYear("2019").setScore(99.0));
scoreList.add(new Score().setStudentId("002").setScoreYear("2018").setScore(99.6));
//根据scoreYear字段进行分组
Map<String, List<Score>> map = scoreList.stream().collect(
Collectors.groupingBy(
score -> score.getScoreYear()
));
System.out.println(JSONUtil.toJsonPrettyStr(map));
}
}
结果如下
{
"2019": [
{
"studentId": "001",
"score": 59.5,
"scoreYear": "2019"
},
{
"studentId": "001",
"score": 99,
"scoreYear": "2019"
}
],
"2018": [
{
"studentId": "001",
"score": 100,
"scoreYear": "2018"
},
{
"studentId": "002",
"score": 99.6,
"scoreYear": "2018"
}
]
}
手头有一个项目不是java8,看着真眼馋,自己琢磨着用反射实现一个
最终实现的工具类如下
后面还可以改造成LinkedHashMap搞成顺序的
不过现在的key都是String类型的,后面可以根据需求改成int long之类的其他类型
public class ReflectUtil {
public static String COUNT_NULL_KEY = "__null__";
public static <T> Map<String, List<T>> groupListByStr(List<T> list, List<String> fieldNames) {
if (list == null || list.size() == 0) {
return null;
}
if (fieldNames == null || fieldNames.size() == 0) {
return null;
}
Map<String, List<T>> groupMap = new HashMap<String, List<T>>();
for (T t : list) {
String val = null;
for (String fieldName : fieldNames) {
val = ReflectUtil.getStr(t, fieldName);
if (val == null || val.trim().length() == 0) {
continue;
}
}
if (val == null || val.trim().length() == 0) {
val = COUNT_NULL_KEY;
}
List<T> gs = groupMap.get(val);
if (gs == null) {
gs = new ArrayList<T>();
}
gs.add(t);
groupMap.put(val, gs);
}
if (groupMap == null || groupMap.size() == 0) {
return null;
}
return groupMap;
}
public static <T> String getStr(T obj, String fieldName) {
Object val = getVal(obj, fieldName);
if (val instanceof String) {
return (String) val;
}
return null;
}
public static <T> String getStr(T obj, Field field) {
Object val = getVal(obj, field);
if (val instanceof String) {
return (String) val;
}
return null;
}
}