【发布时间】:2019-12-08 15:34:26
【问题描述】:
各位程序员,大家好, 最近是学校,我们被要求学习流 API,我爱上了它们。不幸的是,我不够熟练,无法正确使用它们。我需要使用流通过它们各自的属性过滤大约 23 个建筑物(被视为对象)的低谷。让我演示一下: 这是我的建筑类:
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 对象的示例
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);
}
它返回了一个异常 线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引 0 超出长度 0 的范围。 好像我的 .filter() 写错了,所以它没有传递任何元素。
谁能告诉我如何正确过滤它?
【问题讨论】:
标签: java arraylist filter java-stream