首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何过滤每个元素中有多个成员的ArrayList?

如何过滤每个元素中有多个成员的ArrayList?
EN

Stack Overflow用户
提问于 2021-06-29 22:54:43
回答 3查看 68关注 0票数 0

我有一个函数,可以从文件中读取空气污染数据并将其保存到数组列表中。我想过滤元素并打印结果。

我可以使用ArrayList从System.out.println("1st element " + pollution.get(0))中获得一行,但不知道如何将筛选器应用到单个列。

数据文件如下所示

代码语言:javascript
运行
复制
shanghai        2015-321   15   15   93.8   16
beijing         2015-332   23   270   86   -1

AirPollution类

代码语言:javascript
运行
复制
public class AirPollution {

    private String city;
    private String date;
    private int hour;
    private double pm;             // Particulate matter
    private double humidity;
    private double temperature;

    /** Construct a new AirPollution object */
    public AirPollution(String city, String date, int hour, double pm, double humidity, double temperature) {
        this.city = city;
        this.date = date;
        this.hour = hour;
        this.pm = pm;
        this.humidity = humidity;
        this.temperature = temperature;
    }

    /** Get the PM concentration */
    public double getPM() {return this.pm;}

    public String toString() {
    return this.city + " at " + this.hour + " on " + this.date
    + " Humidity: " + this.humidity + " temperature: " + this.temperature;
    }
}

函数,该函数读取文件并将其保存到数组列表中

代码语言:javascript
运行
复制
public class AirPollutionAnalyser {
    private ArrayList<AirPollution> pollution = new ArrayList<AirPollution>();

    public void loadData() {
       try {
           this.pollution.clear();
           List<String> pollution = Files.readAllLines(Path.of(UIFileChooser.open("pollution.txt")));
           for (String line : pollution) {
               Scanner s = new Scanner(line);
               String city = s.next();
               String date = s.next();
               int hour = s.nextInt();
               double pm = s.nextDouble();
               double humidity = s.nextDouble();
               double temperature = s.nextDouble();
               this.pollution.add(new AirPollution(city, date, hour, pm, humidity, temperature));
            }
           
       } catch(IOException e){UI.println("File reading failed");}
    }

打印出ArrayList中PM2.5浓度300及以上的所有记录。

**这是我想更改的函数。**

代码语言:javascript
运行
复制
    public void findHazardousLevels() {
        UI.clearText();
        UI.println("PM2.5 Concentration 300 and above:");
        UI.println("------------------------");
        System.out.println("1st element " + pollution.get(0))
    }
}

如何通过对当前代码的最小更改来实现结果?谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-06-29 23:45:59

您的类字段中还不清楚PM2.5是什么,但是您可以打印具有这样一个pm >= 300的每个条目。因为您的类字段是私有的,所以它假定您有getter来获取这些字段。

代码语言:javascript
运行
复制
public void findHazardousLevels() {
    UI.clearText();
    UI.println("PM2.5 Concentration 300 and above:");
    UI.println("------------------------");
    for(AirPollution p : pollution) {
       if (p.getPm() >= 300) { 
           System.out.println(p);
       }
    }
}

注意:您的toString()实现在返回的字符串中没有包含pm

票数 3
EN

Stack Overflow用户

发布于 2021-06-29 23:49:45

tl;dr

代码语言:javascript
运行
复制
List.of(
                new AirPollution( "shanghai" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 321 ) , LocalTime.of( 15 , 0 ) ) , 15 , 93.8 , 16 ) ,
                new AirPollution( "beijing" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 322 ) , LocalTime.of( 23 , 0 ) ) , 270 , 86 , - 1 )
        )
        .stream()
        .filter(
                sample -> sample.temperature() <= 0
        )
        .toList();

[AirPollutioncity=beijing,时间=2015-11-18T23:00,particulate_2_5=270.0,humidity=86.0,温度=-1.0]

详细信息

有关使用经典语法的简单解决方案,请参见正确的WJS的答复。要想得到更好但不一定更好的解决方案,请继续阅读。

过滤流

您可以通过使用现代流和lambda语法轻松地过滤List

记录

顺便说一句,在Java16中,您可以使用记录特性来简化类定义。编译器隐式地创建构造函数、getter、equals & hashCodetoString

java.time

在java.time框架中,Java有类来表示您的日期和时间:LocalDateLocalTime,并将两者结合在一起,即LocalDateTimeLocalDate类提供了处理年份输入的ofYearDay方法。

这是你的全班同学:

代码语言:javascript
运行
复制
package work.basil.demo;

import java.time.LocalDateTime;

public record AirPollution( String city , LocalDateTime when , double particulate_2_5 , double humidity , double temperature ) { }

实例化几个。

代码语言:javascript
运行
复制
List < AirPollution > samples =
        List.of(
                new AirPollution( "shanghai" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 321 ) , LocalTime.of( 15 , 0 ) ) , 15 , 93.8 , 16 ) ,
                new AirPollution( "beijing" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 322 ) , LocalTime.of( 23 , 0 ) ) , 270 , 86 , - 1 )
        );

将列表作为流访问,以处理每个元素。调用Stream#filter跳过不合格谓词测试的元素。将传递的元素收集到新列表中。

代码语言:javascript
运行
复制
List < AirPollution > freezing = samples.stream().filter( sample -> sample.temperature() <= 0 ).toList();

在Java 16之前的旧版本中,需要用.toList()替换.collect( Collectors.toList() )调用。

这是完整的演示代码。

代码语言:javascript
运行
复制
package work.basil.demo;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

public class AirPollutionDemo
{
    public static void main ( String[] args )
    {
        List < AirPollution > samples =
                List.of(
                        new AirPollution( "shanghai" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 321 ) , LocalTime.of( 15 , 0 ) ) , 15 , 93.8 , 16 ) ,
                        new AirPollution( "beijing" , LocalDateTime.of( LocalDate.ofYearDay( 2015 , 322 ) , LocalTime.of( 23 , 0 ) ) , 270 , 86 , - 1 )
                );

        List < AirPollution > freezing = samples.stream().filter( sample -> sample.temperature() <= 0 ).toList();

        System.out.println( "samples = " + samples );
        System.out.println( "freezing = " + freezing );
    }
}

跑的时候。

样品= [AirPollutioncity=shanghai,when=2015-11-17T15:00,particulate_2_5=15.0,humidity=93.8,temperature=16.0,AirPollutioncity=beijing,时间=2015-11-18T23:00,particulate_2_5=270.0,humidity=86.0,温度=-1.0] 冻结= [AirPollutioncity=beijing =2015-11-18T23:00,particulate_2_5=270.0,humidity=86.0,温度=-1.0]

票数 1
EN

Stack Overflow用户

发布于 2021-06-29 23:52:37

您有一个对象列表,这些对象具有字段,而不是“列”,您可以遍历它们,并编写一些if-语句来排除/查找您感兴趣的数据。

如果将列表转换为流,则可以调用filter().findFirst()并获取它(如果可用的话)

代码语言:javascript
运行
复制
Predicate<AirPollution> highPm = p -> p.getPM() > 300;

Optional<AirPollution> opt = pollution.stream().filter(highPM).findFirst();

if (opt.isPresent()) {
    System.out.println(opt.get());
} else {
    System.out.println("No high PM found");
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68186539

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档