英文:
How to use IntStream in java 8 to return an ascending arraylist?
问题
我对IntStream还不太熟悉,现在假设我有一个保存了一些实体的ArrayList:
```java
public ArrayList<Entity> entities() {return entities;}
ArrayList<Entity> entities = new ArrayList<>();
然后我创建了一个子类rock,它有x、y和radius作为字段:
record Rock(int x, int y, int radius) implements Entity {
//一些方法
}
现在我想要按照半径从大到小的顺序返回rock:
OptionalInt findRock(ArrayList<Entity> es) {
//这个返回的是按存储顺序排列的rock,但我想要按照半径从大到小的顺序获取rock序列
return IntStream.range(0, es.size())
.filter(i -> es.get(i) instanceof Rock)
.boxed()
.sorted((i1, i2) -> Integer.compare(((Rock) es.get(i2)).radius(), ((Rock) es.get(i1)).radius()))
.mapToInt(i -> i)
.findFirst();
}
例如,如果我有radius == 15
的rock1
,radius == 10
的rock2
,radius == 20
的rock3
,它将返回rock3 -> rock1 -> rock2
。
有办法实现这个吗?谢谢。
<details>
<summary>英文:</summary>
I am quite fresh to the IntStream, now assume I have an Arraylist preserved some entities:
public ArrayList<Entity> entities(){return entities;}
ArrayList<Entity> entities=new ArrayList<>();
Then I created a subclass rock which has x, y, and radius as fields:
record Rock(int x,int y,int radius) implements Entity{
//Some method
}
Now I want to return the rock which radius ordered from big to small:
OptionalInt findRock(ArrayList<Entity> es){
//This one returns the rock in a stored order, but I want get the rock sequence from big radius to small radius
return IntStream.range(0,es.size()).filter(i->es.get(i) instanceof Rock).findFirst();
}
For example, if I have `rock1 which radius == 15`, `rock2 which radius == 10`, `rock3 which radius == 20`, it will return `rock3 -> rock1 -> rock2`
Is there any way to achieve it? Thanks.
</details>
# 答案1
**得分**: 6
你可以像这样实现
```java
entities.stream()
.filter(Rock.class::isInstance)
.map(Rock.class::cast)
.sorted(Comparator.comparingInt(Rock::getRadius))
.forEach(rock -> System.out.println("半径为 " + rock.getRadius()));
如果你想要相反的顺序,可以使用 `Comparator.comparing(Rock::getRadius).reversed()`。你不需要使用 `IntStream`。
英文:
You could do it like this
entities.stream()
.filter(Rock.class::isInstance)
.map(Rock.class::cast)
.sorted(Comparator.comparingInt(Rock::getRadius))
.forEach(rock -> System.out.println("Rock with radius " + rock.getRadius()));
Use Comparator.comparing(Rock::getRadius).reversed()
if you want the opposite order. You don't need an IntStream
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论