Java List stream数据筛选、去重、分组、统计、排序,按小时、天、周、月、年分组统计,最大值、最小值、平均数、求和

本文介绍了Java8引入的StreamAPI,展示了如何使用filter、distinct、sorted和collect方法对集合进行高效、声明式的操作,以及与SQL查询在时间分组上的对比应用。

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

Java 8 API添加了一个新的抽象称为流Stream,可以让你以一种声明的方式处理数据。

Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。

0.数据统计

List<Map<String, Object>> valueList = new ArrayList<>();
Map max = valueList.stream().max(Comparator.comparing(s -> (Double)s.get("value"))).get();
Map min = valueList.stream().min(Comparator.comparing(s -> (Double)s.get("value"))).get();
Double avg = valueList.stream().mapToDouble(s -> (Double)s.get("value")).average().orElse(0D);
Double sum = valueList.stream().mapToDouble(s -> (Double)s.get("value")).sum();

1.过滤元素 - filter()

filter()方法根据给定的条件筛选出符合条件的元素,返回一个新的流。

示例:

List<Dictionaries> dictionaries = list.stream().filter( s -> s.getType().equals("0")).collect(Collectors.toList());

2.去重元素 - distinct()

distinct()方法对流中的元素进行去重

示例:

 // 去重
List<Dictionaries> dictionaries = list.stream().distinct().collect(Collectors.toList());

// 根据名称去重
List<Dictionaries> dictionaries = list.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Work::getRepairDepart))), ArrayList::new)
            );

3.排序元素 - sorted()

sorted()方法对流中的元素进行排序,默认是按照自然顺序排序,也可以传入自定义的比较器;

示例:

// 升序排序
List<Dictionaries> dictionaries = list.stream().sorted().collect(Collectors.toList());

// 降序排序
List<Dictionaries> dictionaries = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

// 定制升序排序
List<Dictionaries> dictionaries = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());

// 定制降序排序
List<Dictionaries> dictionaries = list.stream().sorted(Comparator.comparing(Student::getAge).reverseOrder()).collect(Collectors.toList());

4.收集结果-collect()

collect()方法将流中的元素收集到一个集合中。

示例:

(1)按时间统计:


// 按小时统计
Map<String, Double> stationHH = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM-dd HH").format(item.getTime()), Collectors.summingDouble(Sensorrealtime::getValue)));

// 按天统计
Map<String, Double> stationHH = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM-dd").format(item.getTime()), Collectors.summingDouble(Sensorrealtime::getValue)));

// 按周统计
Map<String, Double> stationHH = list.stream().collect(Collectors.groupingBy(item -> getWeekNumber(item.getTelTime()), Collectors.summingDouble(Sensorrealtime::getValue)));

// 按月统计
Map<String, Double> stationHH = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM").format(item.getTime()), Collectors.summingDouble(Sensorrealtime::getValue)));

// 按年统计
Map<String, Double> stationHH = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy").format(item.getTime()), Collectors.summingDouble(Sensorrealtime::getValue)));

// 获取周数
public String getWeekNumber(Date date){
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    int weekNumber = localDate.get(WeekFields.ISO.weekOfMonth());
    return Integer.toString(weekNumber);
}

(2)按时间分组:


// 按小时分组
Map<String, List<CallRecords>> listHH = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM-dd HH").format(item.getTelTime())));

// 按天分组
Map<String, List<CallRecords>> listDD = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM-dd").format(item.getTelTime())));

// 按周分组
Map<String, List<CallRecords>> listWW = list.stream().collect(Collectors.groupingBy(item -> getWeekNumber(item.getTelTime()))); 

// 按月分组
Map<String, List<CallRecords>> listWW = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy-MM").format(item.getTelTime()))); 

// 按年分组
Map<String, List<CallRecords>> listWW = list.stream().collect(Collectors.groupingBy(item -> new SimpleDateFormat("yyyy").format(item.getTelTime()))); 

// 获取周数
public String getWeekNumber(Date date){
    LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    int weekNumber = localDate.get(WeekFields.ISO.weekOfMonth());
    return Integer.toString(weekNumber);
}
      
                         

其他:

SQL 分时间查询:

下面例子中表名为tablename,条件字段名为inputdate

查询今天

SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=0

查询昨天

SELECT * FROM tablename where DATEDIFF(day,inputdate,GETDATE())=1

查询本周

SELECT * FROM tablename where datediff(week,inputdate,getdate())=0

查询上周

SELECT * FROM tablename where datediff(week,inputdate,getdate())=1

查询本月

SELECT * FROM tablename where DATEDIFF(month,inputdate,GETDATE())=0

查询上月

SELECT * FROM tablename where DATEDIFF(month,inputdate,GETDATE())=1

查询本季度的

select * from T_InterViewInfo where datediff(QQ,inputdate,getdate())=0

### Java Stream API Group By 和 Count 示例 对于给定的一系列对象,可以利用 `Stream` 接口中的方法来执行分组和计数操作。下面是一个具体的例子,展示了如何通过商品名称对列表进行分组并计算每种商品的数量。 假设有一个名为 `Item` 的类,其中包含一个表示物品名称的方法 `getName()`: ```java Map<String, Long> counting = items.stream() .collect(Collectors.groupingBy(Item::getName, Collectors.counting())); ``` 上述代码创建了一个映射表,键为商品名而值则代表该商品出现次数[^1]。这里使用了两个收集器:一个是用于按商品名字串分组 (`Collectors.groupingBy`);另一个则是用来统计分组内元素数量(`Collectors.counting`)。 为了更清晰地理解整个过程的工作原理,考虑如下完整的实例代码片段: ```java import java.util.*; import java.util.stream.Collectors; class Item { private final String name; public Item(String name) { this.name = name; } public String getName() { return name; } @Override public boolean equals(Object o){ if (this == o) return true; if (!(o instanceof Item)) return false; Item item = (Item) o; return Objects.equals(name, item.name); } } public class Main { public static void main(String[] args) { List<Item> items = Arrays.asList( new Item("apple"), new Item("banana"), new Item("orange"), new Item("apple"), new Item("banana") ); Map<String, Long> result = items.stream() .collect(Collectors.groupingBy(Item::getName, Collectors.counting())); System.out.println(result); // 输出: {orange=1, banana=2, apple=2} } } ``` 这段程序定义了一个简单的 `Item` 类以及一组测试数据,在此基础上实现了基于流的操作来进行分组与计数,并最终打印出了结果集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王八八。

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

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

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

打赏作者

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

抵扣说明:

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

余额充值