仅限于装逼用,stream流的一些方法老是记不住,就收集了一些方法用于工具类,以下代码直接复制可用。
package cn.getech.iot.data.collection.utils;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* 用于stream的复用工具类
* @author tt
*/
public class StreamUtils<E> {
/**
* -------------------------------------list转换成map的方法--------------------------------------------
* 将List集合转换为Map
*
* @param <T> 泛型参数,表示输入List中的元素类型
* @param <K> 泛型参数,表示Map的键类型
* @param <V> 泛型参数,表示Map的值类型
* @param list 输入的List集合
* @param keyMapper 获取Map键的映射函数
* @param valueMapper 获取Map值的映射函数
* @return 转换后的Map map
*/
public static <T, K, V> Map<K, V> listToMap(
List<T> list,
Function<T, K> keyMapper,
Function<T, V> valueMapper) {
if (list == null || list.isEmpty()) {
return Collections.emptyMap();
}
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(keyMapper, valueMapper, (k1, k2) -> k2));
}
/**
* 将列表转换为Map,其中列表中的对象作为值,由提供的键提取函数提取键。
*
* @param <K> Map的键类型
* @param <V> Map的值类型
* @param list 要转换为Map的列表
* @param keyMapper 用于从对象中提取键的函数
* @return 生成的Map ,其中键由keyMapper函数提取,值为原始列表中的对象
*/
public static <K, V> Map<K, V> listToMap(
List<V> list,
Function<V, K> keyMapper) {
if (list == null || list.isEmpty()) {
return Collections.emptyMap();
}
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.toMap(keyMapper, v -> v, (k1, k2) -> k2));
}
/**
* 将传入的泛型List集合按照指定字段进行分组,并返回分组后的Map
*
* @param <T> 泛型类型
* @param <K> 分组字段的类型
* @param list 泛型List集合
* @param groupingFunc 用于分组的字段提取函数
* @return 分组后的Map ,Key为字段值,Value为分组后的List
*/
public static <T, K> Map<K, List<T>> groupByField(
List<T> list,
Function<T, K> groupingFunc) {
if (list == null || list.isEmpty()) {
return Collections.emptyMap();
}
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.groupingBy(groupingFunc));
}
/**
* -------------------------------------list转换成list的方法--------------------------------------------
* 从泛型集合中提取指定属性,并返回一个新的泛型集合。
*
* @param list 输入的泛型集合
* @param propertyExtractor 一个函数接口,用于从泛型对象中提取属性
* @param <T> 输入集合的元素类型
* @param <R> 返回集合的元素类型
* @return 包含提取属性结果的新的泛型集合
*/
public static <T, R> List<R> extractListProperty(
List<T> list,
Function<T, R> propertyExtractor) {
if (list == null || list.isEmpty()) {
return Collections.emptyList();
}
return list.stream()
.filter(Objects::nonNull)
.map(propertyExtractor)
.collect(Collectors.toList());
}
/**
* -------------------------------------类似mybatisPlus的操作--------------------------------------------
* 操作的集合
*/
private Collection<E> collection;
/**
* 构造方法
*
* @param collection 操作的集合
*/
private StreamUtils(Collection<E> collection) {
this.collection = collection;
}
/**
* 获取StreamUtils
*
* @param collection 操作的集合
* @param <T> 泛型
* @return StreamUtils
*/
public static <T> StreamUtils<T> from(Collection<T> collection) {
return new StreamUtils<>(collection);
}
/**
* 封装Stream流filter方法
* @param predicate 条件
*/
public StreamUtils<E> filter(Predicate<E> predicate) {
collection = collection.stream().filter(predicate).collect(Collectors.toList());
return this;
}
/**
* 取出某个属性的值
*/
public <R> StreamUtils<R> map(Function<E, R> mapper) {
List<R> result = collection.stream().map(mapper).collect(Collectors.toList());
return new StreamUtils<>(result);
}
/**
* 集合转到map中,以对象其中的一个属性为key
*/
public Map<E, E> toMap(Function<E, E> keyMapper, Function<E, E> valueMapper) {
return collection.stream().collect(Collectors.toMap(keyMapper, valueMapper));
}
/**
* 对集合去重
*/
public StreamUtils<E> distinct() {
collection = collection.stream().distinct().collect(Collectors.toList());
return this;
}
/**
* 取最大
*/
public Optional<E> max(Comparator<E> comparator) {
return collection.stream().max(comparator);
}
/**
* 取最小
*/
public Optional<E> min(Comparator<E> comparator) {
return collection.stream().min(comparator);
}
/**
* 等于
*/
public StreamUtils<E> eq(Function<E, Object> keyExtractor, Object value) {
return filter(obj -> Objects.equals(keyExtractor.apply(obj), value));
}
/**
* 等于
*/
public StreamUtils<E> eq(boolean condition, Function<E, Object> keyExtractor, Object value) {
return condition ? filter(obj -> Objects.equals(keyExtractor.apply(obj), value)) : this;
}
/**
* 是否为null
*/
public StreamUtils<E> isNull(Function<E, Object> keyExtractor) {
return filter(obj -> Objects.isNull(keyExtractor.apply(obj)));
}
/**
* 是否为null
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> isNull(boolean condition, Function<E, Object> keyExtractor) {
return condition ? filter(obj -> Objects.isNull(keyExtractor.apply(obj))) : this;
}
/**
* 是否为空
*/
public StreamUtils<E> isEmpty(Function<E, Object> keyExtractor) {
return filter(obj -> ObjectUtil.isEmpty(keyExtractor.apply(obj)));
}
/**
* 是否为空
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> isEmpty(boolean condition, Function<E, Object> keyExtractor) {
return condition ? filter(obj -> ObjectUtil.isEmpty(keyExtractor.apply(obj))) : this;
}
/**
* 是否不为null
*/
public StreamUtils<E> isNotNull(Function<E, Object> keyExtractor) {
return filter(obj -> Objects.nonNull(keyExtractor.apply(obj)));
}
/**
* 是否不为null
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> isNotNull(boolean condition, Function<E, Object> keyExtractor) {
return condition ? filter(obj -> Objects.nonNull(keyExtractor.apply(obj))) : this;
}
/**
* 是否不为空
*/
public StreamUtils<E> isNotEmpty(Function<E, Object> keyExtractor) {
return filter(obj -> ObjectUtil.isNotEmpty(keyExtractor.apply(obj)));
}
/**
* 是否不为空
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> isNotEmpty(boolean condition, Function<E, Object> keyExtractor) {
return condition ? filter(obj -> ObjectUtil.isNotEmpty(keyExtractor.apply(obj))) : this;
}
/**
* 不等于
*/
public StreamUtils<E> ne(Function<E, Object> keyExtractor, Object value) {
return filter(obj -> !Objects.equals(keyExtractor.apply(obj), value));
}
/**
* 不等于
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> ne(boolean condition, Function<E, Object> keyExtractor, Object value) {
return condition ? filter(obj -> !Objects.equals(keyExtractor.apply(obj), value)) : this;
}
/**
* 大于等于
*/
public <U extends Comparable<U>> StreamUtils<E> ge(Function<E, U> keyExtractor, U threshold) {
return filter(obj -> {
U value = keyExtractor.apply(obj);
return null != value && value.compareTo(threshold) >= 0;
});
}
/**
* 大于等于
* @param condition 判断是否参与查询的条件
*/
public <U extends Comparable<U>> StreamUtils<E> ge(boolean condition, Function<E, U> keyExtractor, U threshold) {
return condition ? filter(obj -> {
U value = keyExtractor.apply(obj);
return null != value && value.compareTo(threshold) >= 0;
}) : this;
}
/**
* 大于
*/
public <U extends Comparable<U>> StreamUtils<E> gt(Function<E, U> keyExtractor, U threshold) {
// return filter(obj -> keyExtractor.apply(obj).compareTo(threshold) > 0);
return filter(obj -> {
U value = keyExtractor.apply(obj);
return value != null && value.compareTo(threshold) > 0;
});
}
/**
* 大于
* @param condition 判断是否参与查询的条件
*/
public <U extends Comparable<U>> StreamUtils<E> gt(boolean condition, Function<E, U> keyExtractor, U threshold) {
return condition ? filter(obj -> {
U value = keyExtractor.apply(obj);
return null != value && value.compareTo(threshold) > 0;
}) : this;
}
/**
* 小于等于
*/
public <U extends Comparable<U>> StreamUtils<E> le(Function<E, U> keyExtractor, U threshold) {
return filter(obj -> {
U value = keyExtractor.apply(obj);
return null != value && value.compareTo(threshold) <= 0;
});
}
/**
* 小于等于
* @param condition 判断是否参与查询的条件
*/
public <U extends Comparable<U>> StreamUtils<E> le(boolean condition, Function<E, U> keyExtractor, U threshold) {
return condition ? filter(obj -> {
U value = keyExtractor.apply(obj);
return null != value && value.compareTo(threshold) <= 0;
}) : this;
}
/**
* 小于
*/
public <U extends Comparable<U>> StreamUtils<E> lt(Function<E, U> keyExtractor, U threshold) {
// return filter(obj -> keyExtractor.apply(obj).compareTo(threshold) < 0);
return filter( obj -> {
U value = keyExtractor.apply(obj);
return value != null && value.compareTo(threshold) < 0;
});
}
/**
* 小于
* @param condition 判断是否参与查询的条件
*/
public <U extends Comparable<U>> StreamUtils<E> lt(boolean condition, Function<E, U> keyExtractor, U threshold) {
return condition ? filter(obj -> {
U value = keyExtractor.apply(obj);
return value != null && value.compareTo(threshold) < 0;
}) : this;
}
/**
* 模糊查询:%like%
*/
public StreamUtils<E> like(Function<E, String> keyExtractor, String pattern) {
return filter(obj -> {
String fieldValue = keyExtractor.apply(obj);
return fieldValue != null && fieldValue.contains(pattern);
});
}
/**
* 模糊查询:%like%
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> like(boolean condition, Function<E, String> keyExtractor, String pattern) {
return condition ? filter(obj -> {
String fieldValue = keyExtractor.apply(obj);
return fieldValue != null && fieldValue.contains(pattern);
}) : this;
}
/**
* in:包含
*/
public StreamUtils<E> in(Function<E, Object> keyExtractor, Collection<?> values) {
return filter(obj -> {
Object fieldValue = keyExtractor.apply(obj);
return CollUtil.isNotEmpty(values) && values.contains(fieldValue);
});
}
/**
* in:包含
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> in(boolean condition, Function<E, Object> keyExtractor, Collection<?> values) {
return condition ? filter(obj ->
{Object fieldValue = keyExtractor.apply(obj);
return CollUtil.isNotEmpty(values) && values.contains(fieldValue);}) : this;
}
/**
* notIn:不包含
*/
public StreamUtils<E> notIn(Function<E, Object> keyExtractor, Collection<?> values) {
return filter(obj -> {
Object fieldValue = keyExtractor.apply(obj);
return !(CollUtil.isNotEmpty(values) && values.contains(fieldValue));
});
}
/**
* notIn:不包含
* @param condition 判断是否参与查询的条件
*/
public StreamUtils<E> notIn(boolean condition, Function<E, Object> keyExtractor, Collection<?> values) {
return condition ? filter(obj -> {
Object fieldValue = keyExtractor.apply(obj);
return !(CollUtil.isNotEmpty(values) && values.contains(fieldValue));
}) : this;
}
/**
* 查找一个
*/
public Optional<E> getOne(Predicate<E> predicate) {
return collection.stream().filter(predicate).findFirst();
}
/**
* 查找第一个
*/
public E findFirst(Predicate<E> predicate) {
return collection.stream().filter(predicate).findFirst().orElse(null);
}
/**
* 查找第一个
*/
public E findFirst() {
return collection.stream().findFirst().orElse(null);
}
/**
* 查找第一个
*/
public E getOne() {
return collection.isEmpty() ? null : CollUtil.get(collection, 0);
}
/**
* not取反操作,
*/
public StreamUtils<E> not(Predicate<E> predicate) {
return filter(predicate.negate());
}
/**
* 并且 and连接符
*/
public StreamUtils<E> and(StreamUtils<E> other) {
collection.retainAll(other.collection);
return this;
}
/**
* 或者
*/
public StreamUtils<E> or(StreamUtils<E> other) {
other.collection.removeAll(collection);
collection.addAll(other.collection);
return this;
}
/**
* 默认排序,升序
*/
public void orderBy(Comparator<E> comparator) {
collection = CollUtil.sort(collection, comparator);
}
/**
* 排序,可指定排序方式
*
* @param comparator 排序
* @param orderBy 1:降序,0:升序
*/
public StreamUtils<E> orderBy(Comparator<E> comparator, int orderBy) {
if (1 == orderBy) {
collection = CollUtil.sort(collection, comparator.reversed());
} else {
orderBy(comparator);
}
return this;
}
/**
* 排序,可指定排序方式,可以指定条件,条件为true时才执行排序
*
* @param comparator 排序
* @param condition 条件
* @param orderBy 1:降序,0:升序
*/
public StreamUtils<E> orderBy(boolean condition, Comparator<E> comparator, int orderBy) {
if (condition) {
if (1 == orderBy) {
collection = CollUtil.sort(collection, comparator.reversed());
} else {
orderBy(comparator);
}
}
return this;
}
/**
* 降序排序
*
* @param comparator
* * @param condition 条件
*/
public StreamUtils<E> orderByDesc(Comparator<E> comparator) {
collection = CollUtil.sort(collection, comparator.reversed());
return this;
}
/**
* 降序排序
*/
public StreamUtils<E> orderByDesc(boolean condition, Comparator<E> comparator) {
if (condition) {
collection = CollUtil.sort(collection, comparator.reversed());
}
return this;
}
/**
* 获取一个List
*/
public List<E> toList() {
return new ArrayList<>(collection);
}
/**
* 获取一个Set
*/
public Set<E> toSet() {
return new HashSet<>(collection);
}
public static void main(String[] args) {
List<Employee> employeeList = StreamUtils.getEmployeeList();
System.out.println("1.转换map<String,String>======================");
Map<Integer, String> employeeMap = StreamUtils.listToMap(employeeList, Employee::getId, Employee::getName);
System.out.println("2.转换map<String,entity>======================");
Map<Integer, Employee> employeeMapEntry = StreamUtils.listToMap(employeeList, Employee::getId);
System.out.println("3.转换map<String,List<entity>>======================");
Map<Integer, List<Employee>> employeeMapList = StreamUtils.groupByField(employeeList, Employee::getId);
System.out.println("4.取其中一个字段做为集合List<String>======================");
List<String> employeeNameList = StreamUtils.extractListProperty(employeeList, Employee::getName);
System.out.println("5.根据list集合筛选结果集======================");
//筛选name为马化腾的结果集
List<Employee> employees = StreamUtils.from(employeeList)
.eq(Employee::getName, "马化腾")
.toList();
//筛选name为马化腾的结果集
List<Employee> employeeList1 = StreamUtils.from(employeeList)
.eq(CollUtil.isNotEmpty(employeeList), Employee::getName, "马化腾")
.toList();
//筛选name为马化腾的结果集,失效,该情况是查询全部
List<Employee> employeeList2 = StreamUtils
.from(employeeList)
.eq(false, Employee::getName, "马化腾")
.toList();
//筛选name不等于马化腾的结果集
List<Employee> employeeList3 = StreamUtils
.from(employeeList)
.ne(Employee::getName, "马化腾")
.toList();
// 筛选age大于等于20的元素
List<Employee> employeeList4 = StreamUtils
.from(employeeList)
.ge(Employee::getAge, 20)
.toList();
// 筛选age大于等于20的元素,并且安排age降序排序(1:降序,0:升序)
List<Employee> employeeList5 = StreamUtils
.from(employeeList)
.ge(Employee::getAge, 20)
.orderBy(Comparator.comparing(Employee::getAge), 1)
.toList();
// findFirst
Employee employeeList6 = StreamUtils
.from(employeeList)
.ge(Employee::getAge, 20)
.orderBy(Comparator.comparing(Employee::getAge), 1)
.findFirst();
// max方法
Employee employeeList7 = StreamUtils
.from(employeeList)
.max(Comparator.comparing(Employee::getAge, Comparator.nullsFirst(Integer::compareTo))) // 最好加上Comparator.nullsFirst(BigDecimal::compareTo),防止空指针异常。
.orElse(null);
// 筛选出name不为空串的元素
List<Employee> employeeList8 = StreamUtils
.from(employeeList)
.isNotEmpty(Employee::getName)
.toList();
// 筛选出name为空串的元素
List<Employee> employeeList9 = StreamUtils
.from(employeeList)
.isEmpty(Employee::getName)
.toList();
// 筛选出name不为空,或者age大于等于20的元素
List<Employee> employeeList10 = StreamUtils
.from(employeeList)
.isNotEmpty(Employee::getName)
.or(StreamUtils.from(employeeList)
.ge(Employee::getAge, 20))
.toList();
// 筛选出name不为空并且age大于等于50的元素
List<Employee> employeeList11 = StreamUtils
.from(employeeList)
.isNotEmpty(Employee::getName)
.and(StreamUtils.from(employeeList)
.ge(Employee::getAge, 20))
.toList();
// notIn
List<Employee> employeeList12 = StreamUtils
.from(employeeList)
.notIn(Employee::getAge, Arrays.asList(88, 98, 35, 5234))
.toList();
// in
List<Employee> employeeList13 = StreamUtils
.from(employeeList)
.in(Employee::getAge, Arrays.asList(88, 98, 35, 5234))
.toList();
// map方法获取amount属性
List<Integer> employeeList14 = StreamUtils
.from(employeeList)
.map(Employee::getAge)
.toList();
}
public static List<Employee> getEmployeeList(){
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "马化腾", 34, 6000.38));
list.add(new Employee(1002, "马云", 12, 9876.12));
list.add(new Employee(1003, "刘强东", 33, 3000.82));
list.add(new Employee(1004, "雷军", 26, 7657.37));
list.add(new Employee(1005, "李彦宏", 65, 5555.32));
list.add(new Employee(1006, "比尔盖茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
return list;
}
/**
* stream测试实体类
*/
@Data
public static class Employee {
private int id;
private String name;
private int age;
private double salary;
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
}
}