如何在Java 8中使用IntStream返回一个升序的ArrayList?

huangapple go评论82阅读模式
英文:

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 == 15rock1radius == 10rock2radius == 20rock3,它将返回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 -&gt; rock1 -&gt; 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 -&gt; System.out.println(&quot;Rock with radius &quot; + rock.getRadius()));

Use Comparator.comparing(Rock::getRadius).reversed() if you want the opposite order. You don't need an IntStream.

huangapple
  • 本文由 发表于 2020年9月26日 16:04:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64075312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定