Stream是Java8的一大亮點(diǎn),是對(duì)容器對(duì)象功能的增強(qiáng),它專注于對(duì)容器對(duì)象進(jìn)行各種非常便利、高效的 聚合操作(aggregate operation)或者大批量數(shù)據(jù)操作。Stream API借助于同樣新出現(xiàn)的Lambda表達(dá)式,極大的提高編程效率和程序可讀性。同時(shí),它提供串行和并行兩種模式進(jìn)行匯聚操作,并發(fā)模式能夠充分利用多核處理器的優(yōu)勢(shì),使用fork/join并行方式來拆分任務(wù)和加速處理過程。所以說,Java8中首次出現(xiàn)的 java.util.stream是一個(gè)函數(shù)式語言+多核時(shí)代綜合影響的產(chǎn)物。
距離java8發(fā)布已經(jīng)過去很多年了,但是發(fā)現(xiàn)身邊的人大部分對(duì)java8的Stream API的掌握程度還不是很高。同時(shí),對(duì)一些我們常用的操作,使用Stream API實(shí)現(xiàn)還是有點(diǎn)繁瑣,筆者當(dāng)初也是花費(fèi)了很多時(shí)間才將其掌握。比如根據(jù)指定key將list轉(zhuǎn)換為map,或者抽取list中的某個(gè)屬性。
因此,筆者編寫了ListKit這個(gè)工具類,幫助大家更好的享受Stream API + lambda帶來的便利,提升代碼的簡(jiǎn)潔度,讓代碼看起來更加舒服。源碼和使用demo如下,請(qǐng)自取。
ListKit
package com.sliver.kit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* Title: ListKit
* Description: list工具類
*
* @author sliver
* @date 2019年12月23日
*/
public final class ListKit {
public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2);
private ListKit() {
super();
}
/**
* Title: distinct
* Description: 過濾重復(fù)元素
* 2020年6月24日
*
* @param <E>
* @param list
* @param keyFunction
* @return
*/
public static <E> List<E> distinct(List<E> list, Function<E, String> keyFunction) {
Map<String, E> linkedMap = new LinkedHashMap<>();
for (E item : list) {
String key = keyFunction.apply(item);
linkedMap.put(key, item);
}
return new ArrayList<>(linkedMap.values());
}
/**
* Title:findFirst <br>
* Description:獲取第一個(gè)符合過濾條件的對(duì)象,不存在是返回空
*
* @param list 操作的list
* @param predicate 用于判定的函數(shù)
* @return E
* @author sliver
* @date 2021-08-18 20:37
*/
public static <E> E findFirst(List<E> list, Predicate<E> predicate) {
if (isEmpty(list)) {
return null;
}
return list.stream().filter(predicate).findFirst().orElseGet(null);
}
/**
* Title: findFirstRepeatElement
* Description: 獲取第一個(gè)滿足過濾條件的重復(fù)元素(不包含null),若無重復(fù)數(shù)據(jù)則返回Optional.empty()
* Date: 2020年4月14日
*
* @param <E>
* @param list
* @param operator
* @return
*/
public static <E> Optional<E> findFirstRepeatElement(List<E> list, Function<E, String> operator) {
if (isEmpty(list)) {
return Optional.empty();
}
HashSet<String> set = new HashSet<>(capacity(list.size()));
for (E e : list) {
String key = operator.apply(e);
if (Objects.isNull(key)) {
continue;
}
if (set.contains(key)) {
return Optional.ofNullable(e);
}
set.add(key);
}
return Optional.empty();
}
private static <E> boolean isEmpty(List<E> list) {
return Objects.isNull(list) || list.isEmpty();
}
/**
* Title: existRepeatElement
* Description: 判斷是否存在重復(fù)的元素
* Date: 2020年4月14日
*
* @param <E>
* @param list
* @param conditionFunction 判斷條件
* @return
*/
public static <E> boolean existRepeatElement(List<E> list, Function<E, String> conditionFunction) {
return findFirstRepeatElement(list, conditionFunction).isPresent();
}
/**
* Title: filter
* Description: 對(duì)List進(jìn)行過濾,簡(jiǎn)化stream操作
* Date: 2020年2月19日
*
* @param <E>
* @param list
* @param predicate 數(shù)據(jù)過濾函數(shù)
* @return
*/
public static <E> List<E> filter(List<E> list, Predicate<E> predicate) {
if (isEmpty(list)) {
return list;
}
return list.stream().filter(predicate).collect(Collectors.toList());
}
/**
* Title:flat <br>
* Description:list扁平化,過濾空元素
*
* @param list
* @param flatFunction
* @return java.util.List<E2>
* @author sliver
* @date 2021-08-18 20:52
*/
public static <E1, E2> List<E2> flat(List<E1> list, Function<E1, List<E2>> flatFunction) {
List<E2> resultList = new LinkedList<>();
list.forEach(item -> {
final List<E2> value = flatFunction.apply(item);
if (Objects.isNull(value)) {
return;
}
resultList.addAll(value);
});
return resultList;
}
/**
* Title: convert
* Description: 轉(zhuǎn)換list對(duì)象為指定類型,跳過null
* 2020年2月4日
*
* @param <E1>
* @param <E2>
* @param list
* @param convertFunction
* @return
*/
public static <E1, E2> List<E2> convert(List<E1> list, Function<E1, E2> convertFunction) {
return getField(list, convertFunction);
}
/**
* Title: getField
* Description: 獲取指定字段,跳過null
* Date: 2020年4月29日
*
* @param <T>
* @param <F>
* @param list
* @param operator
* @return
*/
public static <T, F> List<F> getField(List<T> list, Function<T, F> operator) {
List<F> fields = new ArrayList<>(list.size());
list.forEach(item -> {
final F value = operator.apply(item);
if (Objects.isNull(value)) {
return;
}
fields.add(value);
});
return fields;
}
/**
* Title: getFieldSet
* Description:獲取指定字段集合,跳過null
* Date: 2020年4月29日
*
* @param <T>
* @param <F>
* @param list
* @param getFunction
* @return
*/
public static <T, F> Set<F> getFieldSet(List<T> list, Function<T, F> getFunction) {
Set<F> fieldSet = new HashSet<>(capacity(list.size()));
list.forEach(item -> {
final F value = getFunction.apply(item);
if (Objects.isNull(value)) {
return;
}
fieldSet.add(value);
});
return fieldSet;
}
/**
* Title: getFieldStr
* Description: 將list中的字段使用,連接成字符串,跳過null和空字符串
* Date: 2020年3月3日
*
* @param <O>
* @param list
* @param getFunction
* @return
*/
public static <O> String getFieldStr(List<O> list, Function<O, String> getFunction) {
return getFieldStr(list, getFunction, ",");
}
/**
* Title:getFieldStr <br>
* Description:將將list中的字段使用指定分隔符連接成字符串,跳過null和空字符串
*
* @param list
* @param getFunction
* @param split 分隔符
* @return java.lang.String
* @author sliver
* @date 2021-08-18 21:06
*/
public static <O> String getFieldStr(List<O> list, Function<O, String> getFunction, String split) {
if (Objects.isNull(split)) {
throw new IllegalArgumentException("split cannot be null");
}
if (isEmpty(list)) {
return "";
}
StringBuilder sb = new StringBuilder();
for (O item : list) {
final String value = getFunction.apply(item);
if (isBlank(value)) {
continue;
}
sb.append(value).append(split);
}
if (sb.length() == 0) {
return "";
}
return sb.delete(sb.length() - 1, sb.length()).toString();
}
private static boolean isBlank(String value) {
return Objects.isNull(value) || Objects.equals(value, "");
}
/**
* Title: convertToMap
* Description: 轉(zhuǎn)換list為map,key值跳過空字符串和null
* Date: 2020年4月29日
*
* @param <O>
* @param list
* @param keyFunction
* @return
*/
public static <O> Map<String, O> convertToMap(List<O> list, Function<O, String> keyFunction) {
if (isEmpty(list)) {
return new HashMap<>();
}
Map<String, O> resultMap = new HashMap<>(capacity(list.size()));
list.forEach(item -> {
final String key = keyFunction.apply(item);
if (isBlank(key)) {
return;
}
resultMap.put(key, item);
});
return resultMap;
}
/**
* Title: convertToMap
* Description: 轉(zhuǎn)換list為map,key值跳過空字符串和null
* Date: 2020年4月29日
*
* @param list
* @param keyFunction
* @param valueFunction
* @return
*/
public static <K, V, E> Map<K, V> convertToMap(List<E> list, Function<E, K> keyFunction, Function<E, V> valueFunction) {
if (isEmpty(list)) {
return new HashMap<>();
}
Map<K, V> resultMap = new HashMap<>(capacity(list.size()));
list.forEach(item -> resultMap.put(keyFunction.apply(item), valueFunction.apply(item)));
return resultMap;
}
/**
* Title: convertToMap
* Description: 轉(zhuǎn)換list為map,key值跳過空字符串和null
* Date: 2020年4月29日
*
* @param list
* @param keyFunction
* @return
* @see #convertToMap(List, Function, Function)
*/
public static <E, K> Map<K, E> convert2Map(List<E> list, Function<E, K> keyFunction) {
if (isEmpty(list)) {
return new HashMap<>();
}
Map<K, E> resultMap = new HashMap<>(capacity(list.size()));
list.forEach(item -> {
final K key = keyFunction.apply(item);
if (Objects.isNull(key)) {
return;
}
resultMap.put(key, item);
});
return resultMap;
}
/**
* Title: mergeToMap
* Description: 合并相同項(xiàng)
* Date: 2020年2月19日
*
* @param <K> 鍵的類型
* @param <E> 對(duì)象的類型
* @param list 操作的集合
* @param keyFunction 獲取key的函數(shù)
* @param mergeFunction 合并相同key項(xiàng)的行數(shù), 參數(shù) 當(dāng)前項(xiàng),已存在的相同項(xiàng)(可能為空)
* @reEurn
* @see #merge(List, Function, BiFunction, Function)
*/
public static <K, E> List<E> merge(List<E> list, Function<E, K> keyFunction, BiFunction<E, E, E> mergeFunction) {
return merge(list,keyFunction,mergeFunction,e->e);
}
/**
* Title:merge <br>
* Description:根據(jù)指定規(guī)則對(duì)list中的項(xiàng)進(jìn)行合并
*
* @param <K> 鍵的類型
* @param <E> 對(duì)象的類型
* @param list 操作的集合
* @param keyFunction 獲取key的函數(shù)
* @param mergeFunction 合并相同key項(xiàng)的行數(shù), 參數(shù) 當(dāng)前項(xiàng),已存在的相同項(xiàng)(可能為空)
* @param initValFunction 對(duì)象初始化函數(shù)
* @return java.util.List<R>
* @author sliver
* @date 2021-08-21 17:22
*/
public static <K, E, R> List<R> merge(List<E> list, Function<E, K> keyFunction, BiFunction<E, R, R> mergeFunction, Function<E, R> initValFunction) {
Map<K, R> map = mergeToMap(list, keyFunction, mergeFunction, initValFunction);
return new ArrayList<>(map.values());
}
/**
* Title: merge2Map
* Description: 合并相同項(xiàng)轉(zhuǎn)換為map
* Date: 2020年5月29日
*
* @param <K>
* @param <E>
* @param <R>
* @param list 數(shù)據(jù)源
* @param keyFunction 提供key的函數(shù)
* @param mergeFunction 做合并操作的函數(shù)
* @param initValFunction 當(dāng)key對(duì)應(yīng)的value不存在時(shí),用于初始化的函數(shù),走這個(gè)function就不會(huì)走mergeFunction
* @return
*/
public static <K, E, R> Map<K, R> mergeToMap(List<E> list, Function<E, K> keyFunction, BiFunction<E, R, R> mergeFunction, Function<E, R> initValFunction) {
Map<K, R> map = new HashMap<>(capacity(list.size()));
list.forEach(item -> {
K key = keyFunction.apply(item);
R target = map.get(key);
if (Objects.isNull(target)) {
target = initValFunction.apply(item);
map.put(key, target);
} else {
map.put(key, mergeFunction.apply(item, target));
}
});
return map;
}
/**
* Title: groupToMap
* Description: 根據(jù)指定規(guī)則將list聚合為Map,過濾空值
* Date: 2020年3月18日
*
* @param <K>
* @param <E>
* @param list
* @param keyFunction
* @return
*/
public static <K, E> Map<K, List<E>> groupToMap(List<E> list, Function<E, K> keyFunction) {
return groupToMap(list, keyFunction, e -> e);
}
/**
* Title: groupToMap
* Description: 根據(jù)指定key函數(shù)和value函數(shù)將list聚合為Map,過濾空值
* Date: 2020年3月18日
*
* @param <K>
* @param <E>
* @param list
* @param keyFunction
* @param valueFunction
* @return
*/
public static <K, E, R> Map<K, List<R>> groupToMap(List<E> list, Function<E, K> keyFunction, Function<E, R> valueFunction) {
Map<K, List<R>> map = new HashMap<>(capacity(list.size()));
list.forEach(item -> {
K key = keyFunction.apply(item);
List<R> target = map.get(key);
if (Objects.isNull(target)) {
target = new ArrayList<>();
map.put(key, target);
}
target.add(valueFunction.apply(item));
});
return map;
}
/**
* Title:setList <br>
* Description:據(jù)關(guān)聯(lián)字段進(jìn)行1對(duì)多設(shè)置值,
*
* @param list1
* @param key1Function
* @param list2
* @param key2Function
* @param setConsumer
* @return void
* @author sliver
* @date 2020-11-19 20:09
*/
public static <E1, E2> void setList(List<E1> list1, Function<E1, String> key1Function, List<E2> list2, Function<E2, String> key2Function, BiConsumer<E1, List<E2>> setConsumer) {
if (isEmpty(list1) || isEmpty(list2)) {
return;
}
Map<String, List<E2>> list2Map = groupToMap(list2, key2Function);
for (E1 e1 : list1) {
String key = key1Function.apply(e1);
List<E2> l2 = list2Map.get(key);
if (!isEmpty(l2)) {
setConsumer.accept(e1, l2);
}
}
}
/**
* Title:set <br>
* Description:根據(jù)關(guān)聯(lián)字段進(jìn)行1對(duì)1或者一對(duì)多設(shè)置值。通常用于一對(duì)多或者一對(duì)一的表的連接
*
* @param list1
* @param key1Function 獲取list1中與list2的關(guān)聯(lián)字段的函數(shù)
* @param list2
* @param key2Function 獲取list2中與list1的關(guān)聯(lián)字段的函數(shù)
* @param setConsumer 設(shè)置值的函數(shù)
* @return void
* @author sliver
* @date 2020-11-19 20:09
*/
public static <E1, E2> void set(List<E1> list1, Function<E1, String> key1Function, List<E2> list2, Function<E2, String> key2Function, BiConsumer<E1, E2> setConsumer) {
if (isEmpty(list1) || isEmpty(list2)) {
return;
}
Map<String, E2> list2Map = convert2Map(list2, key2Function);
for (E1 e1 : list1) {
String key = key1Function.apply(e1);
E2 e2 = list2Map.get(key);
if (Objects.nonNull(e2)) {
setConsumer.accept(e1, e2);
}
}
}
/**
* Returns a capacity that is sufficient to keep the map from being resized as
* long as it grows no larger than expectedSize and the load factor is >= its
* default (0.75).
*/
static int capacity(int expectedSize) {
if (expectedSize < MAX_POWER_OF_TWO) {
return expectedSize + expectedSize / 3;
}
// any large value
return Integer.MAX_VALUE;
}
}
使用示例 ListKitDemo
package com.sliver.kit;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/**
* <p>Title: ListKitDemo</p>
* <p>Description: ListKit使用實(shí)例</p>
* 我們使用學(xué)生對(duì)象和成績(jī)表對(duì)象進(jìn)行演示,它們的關(guān)系是一對(duì)多的關(guān)系,
* 以下demo根據(jù)使用頻次進(jìn)行排序
*
* @author sliver
* @email 18142611739@163.com
* @date 2021-08-21 16:43
*/
public class ListKitDemo {
private static List<Student> studentList;
private static List<Grade> gradeList;
static void initData(){
// 數(shù)據(jù)準(zhǔn)備
studentList = new ArrayList<>();
studentList.add(new Student("001", "張三"));
studentList.add(new Student("002", "李四"));
studentList.add(new Student("003", "王五"));
gradeList = new ArrayList<>();
gradeList.add(new Grade("001", "數(shù)學(xué)", 88));
gradeList.add(new Grade("001", "語文", 78));
gradeList.add(new Grade("001", "英語", 90));
gradeList.add(new Grade("002", "數(shù)學(xué)", 83));
gradeList.add(new Grade("002", "語文", 73));
gradeList.add(new Grade("002", "英語", 93));
gradeList.add(new Grade("003", "數(shù)學(xué)", 85));
gradeList.add(new Grade("003", "語文", 75));
gradeList.add(new Grade("003", "英語", 95));
}
public static void main(String[] args) {
System.out.println("=======testConvert=======");
testConvert();
System.out.println("\n=======testGroup=======");
testGroup();
System.out.println("\n=======testMerge=======");
testMerge();
System.out.println("\n=======testSet=======");
testSet();
System.out.println("\n=======testOther=======");
testOther();
}
/**
* Title:testConvert <br>
* Description:演示convert、convertToMap的用法
*
* @return void
* @date 2021-08-21 17:33
*/
static void testConvert() {
initData();
// 使用ListKit.convert從students中獲取學(xué)生姓名數(shù)組,也可以用ListKit.getField,與convert的實(shí)現(xiàn)一致,在此場(chǎng)景下更符合語義
List<String> nameList = ListKit.convert(studentList, Student::getCode);
System.out.println("ListKit.convert(studentList, Student::getCode):");
System.out.println(nameList);
// 從gradeList中獲取有分?jǐn)?shù)的學(xué)生編號(hào)
Set<String> studentCodeSet = ListKit.getFieldSet(gradeList, Grade::getStudentCode);
System.out.println("ListKit.getFieldSet(gradeList, Grade::getStudentCode):");
System.out.println(studentCodeSet);
// 將studentList轉(zhuǎn)換為map,使用code作為key
Map<String, Student> studentMap = ListKit.convert2Map(studentList, Student::getCode);
System.out.println("ListKit.convert2Map(studentList, Student::getCode):");
System.out.println(studentMap);
// 將gradeList轉(zhuǎn)換為map,使用studentCode+course作為key
Map<String, Grade> gradeMap = ListKit.convert2Map(gradeList, e -> e.getStudentCode() + e.getCourse());
System.out.println("ListKit.convert2Map(gradeList, e -> e.getStudentCode() + e.getCourse()):");
System.out.println(gradeMap);
}
/**
* Title:testGroup <br>
* Description:測(cè)試分組相關(guān)方法
*
* @return void
* @date 2021-08-21 17:42
*/
static void testGroup() {
initData();
// 1. 將gradeList按studentCode分組
Map<String, List<Grade>> gradeListMap = ListKit.groupToMap(gradeList, Grade::getStudentCode);
System.out.println("ListKit.groupToMap(gradeList, Grade::getStudentCode):");
System.out.println(gradeListMap);
// 2. 將gradeList按studentCode分組,并且將value轉(zhuǎn)換為score
Map<String, List<Integer>> gradeListMap2 = ListKit.groupToMap(gradeList, Grade::getStudentCode, Grade::getScore);
System.out.println("ListKit.groupToMap(gradeList, Grade::getStudentCode, Grade::getScore):");
System.out.println(gradeListMap2);
}
/**
* Title:testMerge <br>
* Description:測(cè)試合并方法
*
* @return void
* @date 2021-08-21 17:51
*/
static void testMerge() {
initData();
// 1. 計(jì)算每個(gè)學(xué)生的總分
List<Integer> gradeList = ListKit.merge(ListKitDemo.gradeList, Grade::getStudentCode, (item, target) -> target + item.getScore(), e -> e.getScore());
System.out.println("ListKit.merge(gradeList, Grade::getStudentCode, (item, target) -> target+ item.getScore(), e -> e.getScore())");
System.out.println(gradeList);
Map<String, Integer> gradeMap = ListKit.mergeToMap(ListKitDemo.gradeList, Grade::getStudentCode, (item, target) -> target + item.getScore(), e -> e.getScore());
System.out.println("ListKit.mergeToMap(ListKitDemo.gradeList, Grade::getStudentCode, (item, target) -> target + item.getScore(), e -> e.getScore())");
System.out.println(gradeMap);
// 2. 將gradeList按studentCode分組,并且將value轉(zhuǎn)換為score
Map<String, List<Integer>> gradeListMap2 = ListKit.groupToMap(ListKitDemo.gradeList, Grade::getStudentCode, Grade::getScore);
System.out.println("ListKit.groupToMap(gradeList, Grade::getStudentCode, Grade::getScore):");
System.out.println(gradeListMap2);
}
/**
* Title:testSet <br>
* Description:測(cè)試set方法,復(fù)合操作
*
* @return void
* @date 2021-08-21 18:04
*/
static void testSet() {
initData();
// 將gradeList放入studentList中
ListKit.setList(studentList, Student::getCode, gradeList, Grade::getStudentCode, (student, gradeList) -> student.setScoreList(gradeList));
System.out.println("ListKit.setList(studentList,Student::getCode,gradeList,Grade::getStudentCode,(student, gradeList)->student.setScoreList(gradeList))");
System.out.println(studentList);
// 設(shè)置總分?jǐn)?shù)
List<Grade> gradeList = ListKit.merge(ListKitDemo.gradeList, Grade::getStudentCode, (item, target) -> target.setScore(target.getScore() + item.getScore()));
ListKit.set(studentList, Student::getCode, gradeList, Grade::getStudentCode, (student, grade) -> student.setTotalScore(grade.getScore()));
System.out.println("ListKit.set(studentList, Student::getCode, gradeList, Grade::getStudentCode, (student, grade) -> student.setTotalScore(grade.getScore()))");
System.out.println(studentList);
}
/**
* Title:testOther <br>
* Description:測(cè)試其它方法
*
* @return void
* @date 2021-08-21 18:14
*/
static void testOther() {
initData();
studentList.add(new Student("002", "李四"));
// 1. 獲取張三的信息
Student student = ListKit.findFirst(studentList, e -> Objects.equals(e.getName(), "張三"));
System.out.println("ListKit.findFirst(studentList, e -> Objects.equals(e.getName(), \"張三\"))");
System.out.println(student);
// 2. 獲取重復(fù)信息
// 判斷是否存在重復(fù)信息
boolean existRepeatElement = ListKit.existRepeatElement(studentList, Student::getCode);
System.out.println("ListKit.existRepeatElement(studentList, Student::getCode)");
System.out.println(existRepeatElement);
Optional<Student> optional = ListKit.findFirstRepeatElement(studentList, Student::getCode);
System.out.println("ListKit.findFirstRepeatElement(studentList,Student::getCode)");
optional.ifPresent(e -> System.out.println(e));
// 3. 排除重復(fù)信息
List<Student> studentList2 = ListKit.distinct(studentList, Student::getCode);
System.out.println("ListKit.distinct(studentList2, Student::getCode)");
System.out.println(studentList2);
// 4. 獲取分?jǐn)?shù)大于80的信息
List<Grade> gradeList2 = ListKit.filter(ListKitDemo.gradeList, grade -> grade.getScore() > 80);
System.out.println("ListKit.filter(ListKitDemo.gradeList, grade -> grade.getScore() > 80)");
System.out.println(gradeList2);
// 5. 將list中的list拉平
ListKit.setList(studentList, Student::getCode, gradeList, Grade::getStudentCode, (stu, gradeList) -> stu.setScoreList(gradeList));
List<Grade> gradeList1 = ListKit.flat(studentList, Student::getScoreList);
System.out.println(" ListKit.flat(studentList, Student::getScoreList)");
System.out.println(gradeList1);
}
}
class Student {
/**
* 學(xué)號(hào)
*/
private String code;
/**
* 姓名
*/
private String name;
private Integer totalScore;
private List<Grade> scoreList;
public Student(String code, String name) {
this.code = code;
this.name = name;
}
public Integer getTotalScore() {
return totalScore;
}
public Student setTotalScore(Integer totalScore) {
this.totalScore = totalScore;
return this;
}
public String getCode() {
return code;
}
public Student setCode(String code) {
this.code = code;
return this;
}
public String getName() {
return name;
}
public Student setName(String name) {
this.name = name;
return this;
}
public List<Grade> getScoreList() {
return scoreList;
}
public Student setScoreList(List<Grade> scoreList) {
this.scoreList = scoreList;
return this;
}
@Override
public String toString() {
return "Student{" +
"code='" + code + '\'' +
", name='" + name + '\'' +
", scoreList=" + scoreList +
'}';
}
}
class Grade {
/**
* 學(xué)生編號(hào)
*/
private String studentCode;
/**
* 課程
*/
private String course;
/**
* 分?jǐn)?shù)
*/
private Integer score;
public Grade(String studentCode, String course, Integer score) {
this.studentCode = studentCode;
this.course = course;
this.score = score;
}
public String getStudentCode() {
return studentCode;
}
public Grade setStudentCode(String studentCode) {
this.studentCode = studentCode;
return this;
}
public String getCourse() {
return course;
}
public Grade setCourse(String course) {
this.course = course;
return this;
}
public Integer getScore() {
return score;
}
public Grade setScore(Integer score) {
this.score = score;
return this;
}
@Override
public String toString() {
return "Grade{" +
"studentCode='" + studentCode + '\'' +
", course='" + course + '\'' +
", score='" + score + '\'' +
'}';
}
}
demo方法運(yùn)行結(jié)果
=======testConvert=======
ListKit.convert(studentList, Student::getCode):
[001, 002, 003]
ListKit.getFieldSet(gradeList, Grade::getStudentCode):
[001, 002, 003]
ListKit.convert2Map(studentList, Student::getCode):
{001=Student{code='001', name='張三', scoreList=null}, 002=Student{code='002', name='李四', scoreList=null}, 003=Student{code='003', name='王五', scoreList=null}}
ListKit.convert2Map(gradeList, e -> e.getStudentCode() + e.getCourse()):
{001數(shù)學(xué)=Grade{studentCode='001', course='數(shù)學(xué)', score='88'}, 002語文=Grade{studentCode='002', course='語文', score='73'}, 003語文=Grade{studentCode='003', course='語文', score='75'}, 003英語=Grade{studentCode='003', course='英語', score='95'}, 002英語=Grade{studentCode='002', course='英語', score='93'}, 001英語=Grade{studentCode='001', course='英語', score='90'}, 001語文=Grade{studentCode='001', course='語文', score='78'}, 003數(shù)學(xué)=Grade{studentCode='003', course='數(shù)學(xué)', score='85'}, 002數(shù)學(xué)=Grade{studentCode='002', course='數(shù)學(xué)', score='83'}}
=======testGroup=======
ListKit.groupToMap(gradeList, Grade::getStudentCode):
{001=[Grade{studentCode='001', course='數(shù)學(xué)', score='88'}, Grade{studentCode='001', course='語文', score='78'}, Grade{studentCode='001', course='英語', score='90'}], 002=[Grade{studentCode='002', course='數(shù)學(xué)', score='83'}, Grade{studentCode='002', course='語文', score='73'}, Grade{studentCode='002', course='英語', score='93'}], 003=[Grade{studentCode='003', course='數(shù)學(xué)', score='85'}, Grade{studentCode='003', course='語文', score='75'}, Grade{studentCode='003', course='英語', score='95'}]}
ListKit.groupToMap(gradeList, Grade::getStudentCode, Grade::getScore):
{001=[88, 78, 90], 002=[83, 73, 93], 003=[85, 75, 95]}
=======testMerge=======
ListKit.merge(gradeList, Grade::getStudentCode, (item, target) -> target+ item.getScore(), e -> e.getScore())
[256, 249, 255]
ListKit.mergeToMap(ListKitDemo.gradeList, Grade::getStudentCode, (item, target) -> target + item.getScore(), e -> e.getScore())
{001=256, 002=249, 003=255}
ListKit.groupToMap(gradeList, Grade::getStudentCode, Grade::getScore):
{001=[88, 78, 90], 002=[83, 73, 93], 003=[85, 75, 95]}
=======testSet=======
ListKit.setList(studentList,Student::getCode,gradeList,Grade::getStudentCode,(student, gradeList)->student.setScoreList(gradeList))
[Student{code='001', name='張三', scoreList=[Grade{studentCode='001', course='數(shù)學(xué)', score='88'}, Grade{studentCode='001', course='語文', score='78'}, Grade{studentCode='001', course='英語', score='90'}]}, Student{code='002', name='李四', scoreList=[Grade{studentCode='002', course='數(shù)學(xué)', score='83'}, Grade{studentCode='002', course='語文', score='73'}, Grade{studentCode='002', course='英語', score='93'}]}, Student{code='003', name='王五', scoreList=[Grade{studentCode='003', course='數(shù)學(xué)', score='85'}, Grade{studentCode='003', course='語文', score='75'}, Grade{studentCode='003', course='英語', score='95'}]}]
ListKit.set(studentList, Student::getCode, gradeList, Grade::getStudentCode, (student, grade) -> student.setTotalScore(grade.getScore()))
[Student{code='001', name='張三', scoreList=[Grade{studentCode='001', course='數(shù)學(xué)', score='256'}, Grade{studentCode='001', course='語文', score='78'}, Grade{studentCode='001', course='英語', score='90'}]}, Student{code='002', name='李四', scoreList=[Grade{studentCode='002', course='數(shù)學(xué)', score='249'}, Grade{studentCode='002', course='語文', score='73'}, Grade{studentCode='002', course='英語', score='93'}]}, Student{code='003', name='王五', scoreList=[Grade{studentCode='003', course='數(shù)學(xué)', score='255'}, Grade{studentCode='003', course='語文', score='75'}, Grade{studentCode='003', course='英語', score='95'}]}]
=======testOther=======
ListKit.findFirst(studentList, e -> Objects.equals(e.getName(), "張三"))
Student{code='001', name='張三', scoreList=null}
ListKit.existRepeatElement(studentList, Student::getCode)
true
ListKit.findFirstRepeatElement(studentList,Student::getCode)
Student{code='002', name='李四', scoreList=null}
ListKit.distinct(studentList2, Student::getCode)
[Student{code='001', name='張三', scoreList=null}, Student{code='002', name='李四', scoreList=null}, Student{code='003', name='王五', scoreList=null}]
ListKit.filter(ListKitDemo.gradeList, grade -> grade.getScore() > 80)
[Grade{studentCode='001', course='數(shù)學(xué)', score='88'}, Grade{studentCode='001', course='英語', score='90'}, Grade{studentCode='002', course='數(shù)學(xué)', score='83'}, Grade{studentCode='002', course='英語', score='93'}, Grade{studentCode='003', course='數(shù)學(xué)', score='85'}, Grade{studentCode='003', course='英語', score='95'}]
ListKit.setList(studentList, Student::getCode, gradeList, Grade::getStudentCode, (student, gradeList) -> student.setScoreList(gradeList))
[Grade{studentCode='001', course='數(shù)學(xué)', score='88'}, Grade{studentCode='001', course='語文', score='78'}, Grade{studentCode='001', course='英語', score='90'}, Grade{studentCode='002', course='數(shù)學(xué)', score='83'}, Grade{studentCode='002', course='語文', score='73'}, Grade{studentCode='002', course='英語', score='93'}, Grade{studentCode='003', course='數(shù)學(xué)', score='85'}, Grade{studentCode='003', course='語文', score='75'}, Grade{studentCode='003', course='英語', score='95'}, Grade{studentCode='002', course='數(shù)學(xué)', score='83'}, Grade{studentCode='002', course='語文', score='73'}, Grade{studentCode='002', course='英語', score='93'}]