• Stream流操作List集合一些常用方法封装


    前言介绍(如果对你有帮助,请给我点点赞)

    当我们在做Java项目时,经常需要对集合进行操作。而对于List集合来说,Stream流提供了一系列便捷的方法,可以帮助我们快速地完成集合的筛选、排序、聚合等操作。但是,由于Stream流的语法比较复杂,有时候会给我们带来一定的困扰。

    为了解决这个问题,我在做项目的过程中,通过学习和总结,封装了一些常用的Stream流操作方法。这些方法可以让我们更加方便地对List集合进行处理,提高开发效率并减少出错的风险。

    在下面的文档中,我将分享这些方法的实现思路和使用方法,希望能够对大家在日常开发中遇到的类似问题有所帮助

    1、方法示例

    批量修改集合对象的某个值

    public static void main(String[] args) {
        //创建假数据, 对象属性为  id ,  name
        TUser u1 = new TUser("1","张三");
        TUser u2 = new TUser("2","李四");
        TUser u3 = new TUser("3","王五");
        TUser u4 = new TUser("4","赵六");
        List<TUser> userList = new ArrayList<>();
        //将对象添加到集合中
        userList.add(u1);userList.add(u2);userList.add(u3);userList.add(u4);
        //TODO 引用【批量修改集合对象的某个值】,实现将集合中所有对象的name修改为 坤哥
        //参数1:要处理的集合
        //参数2:要修改的属性
        //参数3:修改的值
        setListObjectByProperty(userList,TUser::setName,"坤哥");
        for (TUser tUser : userList) {
            System.out.println("修改后的对象:" + tUser);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    输出结果如下:

    修改后的对象:TUser{id='1', name='坤哥'}
    修改后的对象:TUser{id='2', name='坤哥'}
    修改后的对象:TUser{id='3', name='坤哥'}
    修改后的对象:TUser{id='4', name='坤哥'}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、方法封装

    import org.springframework.beans.BeanUtils;
    
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.function.BiConsumer;
    import java.util.function.Function;
    import java.util.function.Predicate;
    import java.util.stream.Collectors;
    
    public class StreamUtils {
    
    
        /**
         * 批量修改集合对象的某个值
         * @param list: 待修改集合
         * @param consumer: 修改属性 泛型属性对象的set方法  Object::set方法
         * @param val: 新值
         * @param : 目标对象泛型
         * @param : 目标值泛型
         */
        public static <T,V> void setListObjectByProperty(List<T> list, BiConsumer<T,V> consumer, V val){
            list.forEach(bean -> consumer.accept(bean,val));
        }
    
        /**
         * 修改集合中满足条件的对象的指定属性的值
         * @param list: 目标集合
         * @param conditionProperty: 条件属性   Objecg::getFiled();
         * @param conditionValue: 条件值
         * @param consumer: 修改的属性 Objecg::setFiled();
         * @param newValue: 修改值
         * @param : 目标对象泛型
         * @param : 目标值泛型
         * @param : 修改值泛型
         */
        public static <T, V, U> void updateListObjByField(
                List<T> list, Function<T, V> conditionProperty,
                V conditionValue, BiConsumer<T, U> consumer, U newValue) {
            list.stream()
                    .filter(element -> conditionProperty.apply(element).equals(conditionValue))
                    .forEach(element -> consumer.accept(element, newValue));
        }
        
        /**
         * 泛型对象的属性setter接口
         *
         * @param  泛型类型
         */
        public interface PropertySetter<T> {
            void set(T target, Object value);
        }
    
        /**
         * List -> List
         * 集合复制 【泛型可以不一样,但是泛型中的属性一样】
         * @param sourceList: 待赋值的集合
         * @param targetType: 泛型.class
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<R> copyList(List<T> sourceList, Class<R> targetType){
            return sourceList.stream()
                    .map( bean -> {
                        try {
                            R target = targetType.getDeclaredConstructor().newInstance();
                            BeanUtils.copyProperties(bean,target);
                            return target;
                        } catch (Exception e) {
                            e.printStackTrace();
                            return null;
                        }
                    }).collect(Collectors.toList());
        }
    
        /**
         * 根据指定条件过滤List集合中指定的元素信息
         * @param inputList: 源list集合
         * @param propertyExtractor: 指定对象过滤的属性  Object::getVal
         * @param values: 过滤属性条件集合值
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<T> filterListByPropertyRemove(List<T> inputList, Function<T, R> propertyExtractor, List<R> values) {
            Predicate<T> condition = item -> !values.contains(propertyExtractor.apply(item));
            return filterList(inputList, condition);
        }
        public static <T> List<T> filterList(List<T> inputList, Predicate<T> condition) {
            return inputList.stream()
                    .filter(condition)
                    .distinct()
                    .collect(Collectors.toList());
        }
    
    	/**
         *根据条件返回集合数据
         * @param inputList: 源list集合
         * @param propertyExtractor: 指定对象的属性  Object::getVal
         * @param values: 属性条件集合值
         * @param 
         * @param 
         * @return
         */
        public <T, R> List<T> filterListByPropertyReturn(List<T> inputList, Function<T, R> propertyExtractor, List<R> values) {
            return inputList.stream()
                .filter(item -> values.contains(propertyExtractor.apply(item)))
                .distinct()
                .collect(Collectors.toList());
        }
    
        /**
         * 【转Map】将集合中对象的属性作为key,val返回
         * @param inputList: 目标list
         * @param keyExtractor: key属性 Object:getObj
         * @param valueExtractor: val属性  Object:getObj
         * @param 
         * @param 
         * @param 
         * @return
         */
        public static <T, K, V> Map<K, V> extractPropertyToMap(List<T> inputList, Function<T, K> keyExtractor, Function<T, V> valueExtractor) {
            return inputList.stream()
                    .collect(Collectors.toMap(keyExtractor, valueExtractor, (v1, v2) -> v2));
        }
    
    	/**
         * 【转Map】指定集合中对象的属性为key,对象本身为val返回
         * @param inputList: 原集合
         * @param keyExtractor: 作为key的属性  Object:getObj
         * @param 
         * @param 
         * @return
         */
    	public <T, K> Map<K, T> extractPropertyToMap(List<T> inputList, Function<T, K> keyExtractor) {
           return inputList.stream()
                .collect(Collectors.toMap(keyExtractor, Function.identity(), (v1, v2) -> v2));
        }
    
    	/**
         * 将List集合按照某个属性进行分组
         * @param inputList: 原集合
         * @param keyExtractor: 分组的属性
         * @param 
         * @param 
         * @return
         */
        public static <T, K> Map<K, List<T>> groupByProperty(List<T> inputList, Function<T, K> keyExtractor) {
            return inputList.stream()
                    .collect(Collectors.groupingBy(keyExtractor));
        }
    
        /**
         * 获取集合中指定元素重复的数据,并返回这个元素的值
         * @param list:源集合
         * @param propertyExtractor: 指定元素  Object::getVal
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<R> findDuplicates(List<T> list, Function<T, R> propertyExtractor) {
            Map<R, Long> propertyCountMap = list.stream()
                    .collect(Collectors.groupingBy(propertyExtractor, Collectors.counting()));
            return propertyCountMap.entrySet().stream()
                    .filter(entry -> entry.getValue() > 1)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());
        }
    
        /**
         * 提取List集合中对象的某个属性并返回集合
         * @param inputList: 目标集合
         * @param propertyExtractor: 泛型对象的属性  Object::getVal
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<R> extractPropertyToList(List<T> inputList, Function<T, R> propertyExtractor) {
            return inputList.stream()
                    .map(propertyExtractor)
                    .collect(Collectors.toList());
        }
        
        /**
         * 提取List集合中对象的某个属性
         * @param inputList: 目标集合
         * @param propertyExtractor: 泛型对象的属性  Object::getVal
         * @param returnType: 返回集合指定泛型  String.class
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<R> extractPropertyToListWithType(List<T> inputList, Function<T, R> propertyExtractor, Class<R> returnType) {
            return inputList.stream()
                    .map(propertyExtractor)
                    .collect(Collectors.toList());
        }
    
        /**
         * 提取List集合中指定条件的属性值
         * @param list:源集合
         * @param filter:指定条件属性  泛型属性对象的get()方法
         * @param mapper:返回属性     泛型属性对象的get()方法
         * @param cls:返回类型
         * @param value:条件值
         * @param 
         * @param 
         * @return
         */
        public static <T, R> List<R> extractPropertyToListWithTypeAndFilter(List<T> list, Function<T, String> filter, Function<T, R> mapper, Class<R> cls, String value) {
            return list.stream()
                    .filter(obj -> filter.apply(obj).equals(value))
                    .map(mapper)
                    .collect(Collectors.toList());
        }
    
        /**
         * 校验集合中对象指定属性的值是否都满足传入条件值
         * @param collection: 源集合
         * @param propertyAccessor: 指定属性 get方法
         * @param expectedValue: 条件值
         * @param 
         * @param 
         * @return
         */
        public static <T, E> boolean validatePropertyAll(Collection<T> collection, Function<T, E> propertyAccessor, E expectedValue) {
            return collection.stream().allMatch(item -> expectedValue.equals(propertyAccessor.apply(item)));
        }
        /**
         * 校验集合中是否有一个对象的属性值满足传入条件值
         * @param collection: 源集合
         * @param propertyAccessor: 指定属性: 指定属性的 get方法
         * @param expectedValue: 条件值
         * @param 
         * @param 
         * @return
         */
        public static <T, E> boolean validatePropertyAny(Collection<T> collection, Function<T, E> propertyAccessor, E expectedValue) {
            return collection.stream().anyMatch(item -> expectedValue.equals(propertyAccessor.apply(item)));
        }
    
    	/**
         * List集合正序排序
         * @param list: 排序集合
         */
        public static void sortPositive(List<String> list) {
            Collections.sort(list);
        }
    
        /**
         * List集合倒序排序
         * @param list: 排序集合
         */
        public static void sortReverse(List<String> list) {
            Collections.sort(list, Collections.reverseOrder());
        }
    
        /**
         * List集合正序排序
         * @param list: 排序集合
         * @param keyExtractor: 对象属性
         * @param 
         */
        public static <T, R extends Comparable<? super R>> void sortPositiveByField(List<T> list, Function<? super T, ? extends R> keyExtractor) {
            Comparator<? super T> comparator = Comparator.comparing(keyExtractor);
            Collections.sort(list, comparator);
        }
    
        /**
         * List集合倒序排序
         * @param list: 排序集合
         * @param keyExtractor: 对象属性
         * @param 
         * @param 
         */
        public static <T, R extends Comparable<? super R>> void sortReverseByField(List<T> list, Function<? super T, ? extends R> keyExtractor) {
            Comparator<? super T> comparator = Comparator.comparing(keyExtractor).reversed();
            Collections.sort(list, comparator);
        }
    
    
    
    
        
    }
    
    
    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174
    • 175
    • 176
    • 177
    • 178
    • 179
    • 180
    • 181
    • 182
    • 183
    • 184
    • 185
    • 186
    • 187
    • 188
    • 189
    • 190
    • 191
    • 192
    • 193
    • 194
    • 195
    • 196
    • 197
    • 198
    • 199
    • 200
    • 201
    • 202
    • 203
    • 204
    • 205
    • 206
    • 207
    • 208
    • 209
    • 210
    • 211
    • 212
    • 213
    • 214
    • 215
    • 216
    • 217
    • 218
    • 219
    • 220
    • 221
    • 222
    • 223
    • 224
    • 225
    • 226
    • 227
    • 228
    • 229
    • 230
    • 231
    • 232
    • 233
    • 234
    • 235
    • 236
    • 237
    • 238
    • 239
    • 240
    • 241
    • 242
    • 243
    • 244
    • 245
    • 246
    • 247
    • 248
    • 249
    • 250
    • 251
    • 252
    • 253
    • 254
    • 255
    • 256
    • 257
    • 258
    • 259
    • 260
    • 261
    • 262
    • 263
    • 264
    • 265
    • 266
    • 267
    • 268
    • 269
    • 270
    • 271
    • 272
    • 273
    • 274
    • 275
    • 276
    • 277
    • 278
    • 279
    • 280
    • 281
    • 282
    • 283
    • 284
    • 285
    • 286
    • 287
    • 288
    • 289
    • 290
    • 291
    • 292
    • 293

  • 相关阅读:
    请问大家有没有软考中项集成的考试技巧?
    实验室安全巡检管理系统—全面安全检查
    物联网微消息队列MQTT介绍-EMQX集群搭建以及与SpringBoot整合
    银行主动安全纵深防御体系解决方案
    Use PlantUML to write the Sequence Diagram
    18-Go语言之单元测试
    前端vue项目部署到云服务器教程
    Java项目:SSM服装进销存管理系统
    [Kubernetes] Istio on Kubernetes 实践
    solidty提升篇-智能协议-合约的所有权-gas-带参数的函数修饰符
  • 原文地址:https://blog.csdn.net/SmallCat0912/article/details/134239860