java8的新特性stream api使用

 

1、使用stream api对list集合做总数累加计算:

List<Integer> profitList = new ArrayList<Integer>();


//使用java8的新特性stream api 做list元素累加,算总和
    int total = profitList.stream().mapToInt(t -> t).sum();

 

 2、使用Stream api对List<map> 类型的集合做某值的总和计算(并且值的类型为BigDecimal类型数值)

List<Integer> doughnutProfitList= new ArrayList<Integer>(); //要处理的list合集

BigDecimal totalValue = new BigDecimal("0"); if(doughnutProfitList != null && doughnutProfitList.size() > 0){ totalValue = doughnutProfitList.stream().map(x -> new BigDecimal(String.valueOf(x.get("score")))).reduce(BigDecimal.ZERO,BigDecimal::add); }

 

 

 3、Stream api过滤LIst<Map<String, Object>> 集合数据,根据条件过滤获取相应的List<Map<String, Object>>集合数据:

复制代码
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String,Object> mapOne = new HashMap<>();
        mapOne.put("id",1 );
        mapOne.put("name","aaa" );
        mapOne.put("age",24 );
        mapOne.put("address","11111" );
        list.add(mapOne);

        Map<String,Object> mapTwo = new HashMap<>();
        mapTwo.put("id",2 );
        mapTwo.put("name","aaa" );
        mapTwo.put("age",18 );
        mapTwo.put("address","22222" );
        list.add(mapTwo);

        Map<String,Object> mapThree = new HashMap<>();
        mapThree.put("id",3 );
        mapThree.put("name","bbb" );
        mapThree.put("age",24 );
        mapThree.put("address","33333" );
        list.add(mapThree);

        //过滤:拿到list<String>
        List<String> listStr =  list.stream().map(item -> item.get("name").toString()).collect(Collectors.toList());
     System.out.println(listStr);

//使用stream api摘出List<Map<String, Object>>集合:过滤得到name为aaa的list集合
        List<Map<String, Object>> newLevel2List = new ArrayList<Map<String,Object>>();
        newLevel2List = list.stream().filter(p ->
           p.get("name").toString().equals("aaa")).collect(Collectors.toList());

        System.out.println(newLevel2List);
复制代码

 

 

 4、list数据使用stream流找出重复的数据:

复制代码
public static <E> List<E> getDuplicateElements(List<E> list) {
        return list.stream() // list 对应的 Stream
                .collect(Collectors.toMap(e -> e, e -> 1, (a, b) -> a + b)) // 获得元素出现频率的 Map,键为元素,值为元素出现的次数
                .entrySet().stream() // 所有 entry 对应的 Stream
                .filter(entry -> entry.getValue() > 1) // 过滤出元素出现次数大于 1 的 entry
                .map(entry -> entry.getKey()) // 获得 entry 的键(重复元素)对应的 Stream
                .collect(Collectors.toList());  // 转化为 List
    }



public static void main(String[] args) throws Exception {


List<String> list = Arrays.asList("a", "b", "c", "d", "a", "a", "d", "d","c","b","e","f");
List<String> duplicateElements = getDuplicateElements(list);

System.out.println("list 中重复的元素:" + duplicateElements);
}





复制代码

 

 

 

 5、求两个List<String>的差集:如:list1 = ['a', 'b', 'c'],list2 = ['b'],返回list1与list2的差集为:['a', 'c']

 

复制代码
/**
    * descript: 求两个list的差集
    * @author: zhouruntao
    * @date: 2023-04-06 20:01
    *
    **/
    public static List<String> subList(List<String> list1, List<String> list2){
        Map<String, String> tempMap = list2.parallelStream().collect(Collectors.toMap(Function.identity(), Function.identity(), (oldData, newData) -> newData));
        return list1.parallelStream().filter(str->{return !tempMap.containsKey(str);}).collect(Collectors.toList());
    }
复制代码

 

 6、使用stream流,提取List<对象>中的某个字段:如id

List<TUser> cList = new ArrayList<TUser>();

List<Long> ids = cList.stream().map(TUser::getId).collect(Collectors.toList());

 

 

7、List<String> 去重

List<String> distinctStrings = strings.stream().distinct().collect(Collectors.toList());

 

8、List<Student> 对象去重:根据Student对象中的studentCode字段属性去重

List<Student> newStudentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student:: getStudentCode))), ArrayList::new));

 

 

9、使用Stream流,提取List中的对象集合,其中name为"abc"的元素对象

(比如:要取List<Student>集合中,把student对象的name值为“abc”的提取出来)

1
2
List<Student> studentList = testVo.getStudentList().stream().filter(studentVo -> "abc".equals(studentVo.getName())).findFirst();
            

  

 

 

 

 

 

 99、按照各种java类型排序

借鉴博物:https://blog.csdn.net/weixin_52796198/article/details/130861941

 

 

 

 

 

 

 

 2024年5月24日更新=====================================================

1、stream流循环简单数组,用来替代for,如操作Long[]数组

            Long[] categoryIds = {1L, 2L, 3L, 4L};
            Arrays.stream(categoryIds).forEach(f->{

                logger.info("==================" + f);

            });

 

 2、stream流循环简单数组,并取下标:使用IntStream.range这个方法

Long[] categoryIds = {1L, 2L, 3L, 4L};
IntStream.range(0, categoryIds.length).forEach(index -> {
                long value = categoryIds[index];
                System.out.println("Index: " + index + ", Value: " + value);
            });

 

 

 3、forEach用表达式-> 操作List<对象>,如下:

复制代码
if (!CollectionUtils.isEmpty(userList)){
            userList.forEach(userObj-> {


    
            //在此循环里,操作循环 出来的对象


    });
}
复制代码

 

 4、将list<对象>转成Map

// nn_navigation表的子类目数据 转成map
                        Map<Long, NavigationDO> navigationMap = navigationDOS.stream().collect(Collectors.toMap(NavigationDO::getId, Function.identity(), (key1, key2) -> key1));
                        //把map的key转成String类型
                        Map<String, NavigationDO> navigationMap2 = navigationMap.entrySet().stream().collect(Collectors.toMap(
                                entry -> entry.getKey().toString(),
                                Map.Entry::getValue));

 

 

 

 5、Map<String, Student>对象,转成 List<Student>数据

1
2
//先从缓存取<br>Map<String, ItemBaseInfo> thirdStateCacheMap = (Map<String, ItemBaseInfo>) cacheManager.batchGetAsMap(keyList);<br><br><br>//缓存中取到的map集合转成List<>对象,并且过滤掉value为null的空数据
            itemBaseInfoList = thirdStateCacheMap.values().stream().filter(Objects::nonNull).collect(Collectors.toList());

  

 

 

 6、list使用stream过滤条件取数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//========================================================================list取数据
        Person p = new Person();
        p.setName("aaa");
        p.setId(1);
 
       Person p2 = new Person();
        p2.setName("bbb");
        p2.setId(2);
 
        List<Person> pList = new ArrayList<Person>();
        pList.add(p);
        pList.add(p2);
 
        List<Person> ps = pList.stream().filter(a -> a.getName().equals("bbb") && a.getId() == 2).collect(Collectors.toList());
 
        ps.forEach(System.out::println);

  

 

 

 

 

 

 

 

.

posted @   下课后我要去放牛  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
历史上的今天:
2018-09-17 判断String类型字符串是否为空的方法
点击右上角即可分享
微信分享提示