我有一个函数,可以从文件中读取空气污染数据并将其保存到数组列表中。我想过滤元素并打印结果。
我可以使用ArrayList从System.out.println("1st element " + pollution.get(0))
中获得一行,但不知道如何将筛选器应用到单个列。
数据文件如下所示
shanghai 2015-321 15 15 93.8 16
beijing 2015-332 23 270 86 -1
AirPollution类
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;
}
}
函数,该函数读取文件并将其保存到数组列表中
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及以上的所有记录。
**这是我想更改的函数。**
public void findHazardousLevels() {
UI.clearText();
UI.println("PM2.5 Concentration 300 and above:");
UI.println("------------------------");
System.out.println("1st element " + pollution.get(0))
}
}
如何通过对当前代码的最小更改来实现结果?谢谢
发布于 2021-06-29 23:45:59
您的类字段中还不清楚PM2.5
是什么,但是您可以打印具有这样一个pm >= 300
的每个条目。因为您的类字段是私有的,所以它假定您有getter来获取这些字段。
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
。
发布于 2021-06-29 23:49:45
tl;dr
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
& hashCode
和toString
。
java.time
在java.time框架中,Java有类来表示您的日期和时间:LocalDate
、LocalTime
,并将两者结合在一起,即LocalDateTime
。LocalDate
类提供了处理年份输入的ofYearDay
方法。
这是你的全班同学:
package work.basil.demo;
import java.time.LocalDateTime;
public record AirPollution( String city , LocalDateTime when , double particulate_2_5 , double humidity , double temperature ) { }
实例化几个。
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
跳过不合格谓词测试的元素。将传递的元素收集到新列表中。
List < AirPollution > freezing = samples.stream().filter( sample -> sample.temperature() <= 0 ).toList();
在Java 16之前的旧版本中,需要用.toList()
替换.collect( Collectors.toList() )
调用。
这是完整的演示代码。
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]
发布于 2021-06-29 23:52:37
您有一个对象列表,这些对象具有字段,而不是“列”,您可以遍历它们,并编写一些if-语句来排除/查找您感兴趣的数据。
如果将列表转换为流,则可以调用filter().findFirst()
并获取它(如果可用的话)
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");
}
https://stackoverflow.com/questions/68186539
复制相似问题