gpt4 book ai didi

java - 如何通过属性使用流来过滤对象?

转载 作者:行者123 更新时间:2023-12-01 19:34:10 26 4
gpt4 key购买 nike

各位程序员大家好,最近学校要求我们学习流API,我爱上了它们。不幸的是,我的技术不够熟练,无法正确使用它们。我需要使用流按各自的属性过滤 23 座建筑物(视为对象)。让我演示一下:这是我的建筑类(class):

class Building  {
String color;
int position;
int cost;
int rent;
int owner;

//ArrayList for storing all of the buildings
public static ArrayList<Building> Buildings = new ArrayList<>();

//getter of the position of this building
public int getBuildingPosition() {
return position;
}

//constructor:
public Building(int position, int cost, int rent, String color, int owner) {
Buildings.add(this);
}
}

这是我的建筑对象的示例

Building buld1 = new Building(1, 50, 6, "gray", 0);

现在有趣的是,因为当我尝试通过此流代码过滤它时:

public static Building getBuildingByPosition(int pos) {
List<Building> all = Building.Buildings
.stream()
.filter(x -> x.getBuildingPosition() == pos) // here may be the error
.collect(Collectors.toList());
return all.get(0);
}

它返回了一个异常线程“main”中的异常 java.lang.IndexOutOfBoundsException:索引 0 超出长度 0 的范围。看来我的 .filter() 写得不正确,所以它没有传递任何元素。

有人可以告诉我如何正确过滤它吗?

最佳答案

首先,您将建筑物添加到静态列表中,但您没有初始化该对象,字段都是空的

public Building(int position, int cost, int rent, String color, int owner) {
this.position = position;
this.cost = cost;
this.rent = rent;
this.color = color;
this.owner = owner;
Buildings.add(this);
}

如果您只想返回一个满足过滤器的对象,请使用返回可选值的 findFirst

public static Building getBuildingByPosition(int pos) {
Optional<Building> building = Building.Buildings
.stream()
.filter(x -> x.getBuildingPosition() == pos)
.findFirst();
return building.orElse(null);
}

关于java - 如何通过属性使用流来过滤对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59236973/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com