java stream中Collectors的用法

该代码展示了如何使用Java创建和操作List,包括日期解析、StreamAPI的过滤、映射、收集等操作,以及Collectors的各种方法如toList,toSet,toMap,counting,summarizingInt和groupingBy。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com;

import com.person.Person;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class test {

    public test() throws ParseException {
    }

    public static List<demo> getList() throws ParseException {
        List<demo> personList = new ArrayList<demo>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Date now = new Date();

        personList.add(new demo("小王", "male", sdf.parse("2022-12-13 13:25:07")));
        personList.add(new demo("小孙", "fmale", sdf.parse("2022-12-14 13:25:07")));
        personList.add(new demo("小张", "fmale", sdf.parse("2022-12-15 13:25:07")));
        for (demo e:personList
        ) {
            System.out.println("姓名:"+e.getAzcp0004()+"  ,time"+e.getAzcp0006());
        }
        return personList;
    }
    public static List<Person> getList2() throws ParseException {
        List<Person> personList = new ArrayList<Person>();
        personList.add(new Person("Tom", 8900, 23, "male", "New York"));
        personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
        personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
        personList.add(new Person("Anni", 8200, 24, "female", "New York"));
        personList.add(new Person("Owen", 9500, 25, "male", "New York"));
        personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

        for (Person e:personList
        ) {
            System.out.println("姓名:"+e.getName()+"  ,salary"+e.getSalary());
        }
        return personList;
    }


     /*   public static void main(String[] args) {
            List<Person> personList = new ArrayList<Person>();
            personList.add(new Person("Tom", 8900, 23, "male", "New York"));
            personList.add(new Person("Jack", 7000, 25, "male", "Washington"));
            personList.add(new Person("Lily", 7800, 21, "female", "Washington"));
            personList.add(new Person("Anni", 8200, 24, "female", "New York"));
            personList.add(new Person("Owen", 9500, 25, "male", "New York"));
            personList.add(new Person("Alisa", 7900, 26, "female", "New York"));

            List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
                    .collect(Collectors.toList());
            System.out.print("薪资高于8000美元的员工:" + fiterList);

    }*/

   /* public static void main(String[] args) {
        // import已省略,请自行添加,后面代码亦是
                List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);

                // 遍历输出符合条件的元素
                list.stream().filter(x -> x > 6).forEach(System.out::println);
                // 匹配第一个
                Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
                // 匹配任意(适用于并行流)
                Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
                // 是否包含符合特定条件的元素
                boolean anyMatch = list.stream().anyMatch(x -> x > 6);
                System.out.println("匹配第一个值:" + findFirst.get());
                System.out.println("匹配任意一个值:" + findAny.get());
                System.out.println("是否存在大于6的值:" + anyMatch);
            }
*/
   public static void main(String[] args) throws ParseException {
       List<String> list = Arrays.asList("jack", "bob", "alice", "mark");
       List<String> duplicateList = Arrays.asList("jack", "jack", "alice", "mark");
       List<demo> demos=getList();
       /**
        * Collectors.toList()  将stream转换为list。这里转换的list是ArrayList
        */
       List<String> listResult = demos.stream().map(demo::getAzcp0004).collect(Collectors.toList());
       for ( String  s:listResult
            ) {
           System.out.println("结果tolist(): "+s);
       }
       /**
       * Collectors.toSet() toSet将Stream转换成为set。这里转换的是HashSet。
       */
       Set<String> listset = duplicateList.stream().map(String::toUpperCase).collect(Collectors.toSet());
       for ( String  s:listset
       ) {
           System.out.println("结果toset(): "+s);
       }

       /**
        * Collectors.toMap() toMap接收两个参数,第一个参数是keyMapper,第二个参数是valueMapper:
        */
       Map<demo,String> listmap = demos.stream().collect(Collectors.toMap(Function.identity(),demo::getAzcp0004));

       System.out.println("map结果tomap  "+listmap);
       Set<demo> keys=listmap.keySet();
       for (demo d:keys
            ) {
           System.out.println("遍历map的结果  "+d.getAzcp0004());
       }

       Set<Map.Entry<demo, String>> entityset=listmap.entrySet();
       for (Map.Entry<demo, String> d:entityset
       ) {
           System.out.println("遍历entryset的结果  "+d.getKey()+"  value= "+d.getValue());
       }
/**
 * Collectors.counting() counting主要用来统计stream中元素的个数
 */
       Long countResult = list.stream().collect(Collectors.counting());
       System.out.println("counting的结果 "+countResult);
/**
 *Collectors.summarizingDouble/Long/Int()
 * SummarizingDouble/Long/Int为stream中的元素生成了统计信息,返回的结果是一个统计类
 */
       IntSummaryStatistics intResult = getList2().stream()
               .collect(Collectors.summarizingInt(Person::getSalary));
       System.out.println("intResult的结果为 "+ intResult);
/**
 *Collectors.groupingBy()
 * GroupingBy根据某些属性进行分组,并返回一个Map
 */

       Map<String, Set<demo>> groupByResult = getList().stream()
               .collect(Collectors.groupingBy(demo::getAzcp0005, Collectors.toSet()));
      Set<Map.Entry<String, Set<demo>>> maps= groupByResult.entrySet();
       for ( Map.Entry<String, Set<demo>> e:maps
            ) {
           System.out.println("groupby结果 ,key= "+e.getKey()+"  value的值= "+e.getValue());
       }
/**
 * Collectors.partitioningBy() 按照某条件划分两类
 */
       Map<Boolean, List<demo>> partitionResult = getList().stream()
               .collect(Collectors.partitioningBy(s-> s.getAzcp0005() .equals("male")));
       Set<Boolean> partitionmaps=partitionResult.keySet();
       for (Boolean b:partitionmaps
            ) {
           System.out.println("partitioningBy 结果为"+ partitionResult.get(b));
       }

   }

}

运行结果

姓名:小王  ,timeTue Dec 13 13:25:07 CST 2022
姓名:小孙  ,timeWed Dec 14 13:25:07 CST 2022
姓名:小张  ,timeThu Dec 15 13:25:07 CST 2022
结果tolist(): 小王
结果tolist(): 小孙
结果tolist(): 小张
结果toset(): ALICE
结果toset(): JACK
结果toset(): MARK
map结果tomap  {com.demo@b1bc7ed=小王, com.demo@30dae81=小张, com.demo@7cd84586=小孙}
遍历map的结果  小王
遍历map的结果  小张
遍历map的结果  小孙
遍历entryset的结果  com.demo@b1bc7ed  value= 小王
遍历entryset的结果  com.demo@30dae81  value= 小张
遍历entryset的结果  com.demo@7cd84586  value= 小孙
counting的结果 4
姓名:Tom  ,salary8900
姓名:Jack  ,salary7000
姓名:Lily  ,salary7800
姓名:Anni  ,salary8200
姓名:Owen  ,salary9500
姓名:Alisa  ,salary7900
intResult的结果为 IntSummaryStatistics{count=6, sum=49300, min=7000, average=8216.666667, max=9500}
姓名:小王  ,timeTue Dec 13 13:25:07 CST 2022
姓名:小孙  ,timeWed Dec 14 13:25:07 CST 2022
姓名:小张  ,timeThu Dec 15 13:25:07 CST 2022
groupby结果 ,key= fmale  value的值= [com.demo@76fb509a, com.demo@300ffa5d]
groupby结果 ,key= male  value的值= [com.demo@6576fe71]
姓名:小王  ,timeTue Dec 13 13:25:07 CST 2022
姓名:小孙  ,timeWed Dec 14 13:25:07 CST 2022
姓名:小张  ,timeThu Dec 15 13:25:07 CST 2022
partitioningBy 结果为[com.demo@37bba400, com.demo@179d3b25]
partitioningBy 结果为[com.demo@254989ff]

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Amo@骄纵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值