一、實(shí)現(xiàn):對(duì)已有對(duì)象集合List<Persion> ,需要獲取Persion對(duì)象的字段 name分組, 并對(duì)年齡age字段值做收集
二、字段分組收集方法
?注:由于實(shí)際業(yè)務(wù)只有String類型跟數(shù)字類型,所以只對(duì)String跟Object兩種類型判空文章來源:http://www.zghlxwxcb.cn/news/detail-605636.html
/**
* 分組并字段收集
*
* @param list
* @param groupFunction 類型現(xiàn)在只能為 String or Object
* @param getFiledFunction
* @return
*/
public static <T, K, V> Map<K, Set<V>> groupAndCollectionField(List<T> list, Function<T, K> groupFunction, Function<T, V> getFiledFunction) {
if (Objects.isNull(list)) {
return new HashMap<>();
}
//按寄收類型分組, 并收集區(qū)號(hào)(機(jī)場(chǎng))
Map<K, Set<V>> setMap = list.stream().filter(r-> {
K groupValue = groupFunction.apply(r);
V filedValue = getFiledFunction.apply(r);
//分組判空
boolean groupNull = Objects.isNull(groupValue);
if (!groupNull && groupValue instanceof String) {
groupNull = ((String) groupValue).length() == 0;
}
//字段判空
boolean filedNull = Objects.isNull(filedValue);
if (filedValue instanceof String) {
filedNull = ((String) filedValue).length() == 0;
}
//分組非空 and 字段非空 返回true; 否則返回false
return !groupNull && !filedNull;
})
.collect(Collectors.groupingBy(groupFunction, Collectors.mapping(getFiledFunction, Collectors.toSet())));
return setMap;
}
三、測(cè)試代碼
//場(chǎng)景1
System.out.println("場(chǎng)景1");
List<Persion> persionList = new ArrayList<>();
persionList.add(new Persion(1, "李二", null));
persionList.add(new Persion(2, null, 30));
persionList.add(new Persion(3, "王五", 15));
persionList.add(new Persion(4, "陳十一", 11));
//分組并收集字段
Map<String, Set<Integer>> setMap = Main.groupAndCollectionField(persionList, Persion::getName, Persion::getAge);
//遍歷
setMap.entrySet().stream().forEach(r-> System.out.println(String.format("name:%s; age:%s",r.getKey(),r.getValue())));
System.out.println("");
//場(chǎng)景2
System.out.println("場(chǎng)景2");
persionList = new ArrayList<>();
persionList.add(new Persion(1, "李二", 22));
persionList.add(new Persion(2, "李二", 30));
persionList.add(new Persion(3, "王五", 15));
persionList.add(new Persion(4, "陳十一", 11));
//分組并收集字段
setMap = Main.groupAndCollectionField(persionList, Persion::getName, Persion::getAge);
//遍歷
setMap.entrySet().stream().forEach(r-> System.out.println(String.format("name:%s; age:%s",r.getKey(),r.getValue())));
}
四、結(jié)果
文章來源地址http://www.zghlxwxcb.cn/news/detail-605636.html
到了這里,關(guān)于java 對(duì)List集合中元素對(duì)象按字段分組,并收集指定字段的值的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!