使用轻量级流 API 流获取元素匹配的索引。

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

Get index where the element matches using lightweight stream API stream

问题

我有以下的流,并且正在使用这个来处理流:

String itemDescValue = Stream.of(dtaArr).filter(e ->
                 e.getRateUID().equals(rateUID))
                .map(myObject::getItemDesc)
                .findFirst()
                .orElse(null);

我想要运行一个流来获取匹配值的索引。我知道可以使用一个简单的for循环来实现:

for (int i = 0; i < dtaArr.size(); i++) {
    if (dtaArr.get(i).getItemDesc().equals(itemDescValue)) {
        // 在这里执行操作
    }
}

请问如何使用轻量级流API来获取匹配值的索引呢?

英文:

I have the following stream and I am using this library for streams:

String itemDescValue = Stream.of(dtaArr).filter(e -&gt;
                 e.getRateUID().equals(rateUID))
                .map(myObject::getItemDesc)
                .findFirst()
                .orElse(null);

I would like to run a stream to get the index on when the value matches. I know I can achieve it using a simple for loop:

for(int i=0 ;i &lt; dtaArr.size(); i++)
        {
            if(dtaArr.get(i).getItemDesc().equals(itemDescValue)){
            //do stuff here
        }
}

How would I get the index on when the value matches using the lightweight stream API.

答案1

得分: 1

使用 IntStream.range

OptionalInt idx =
    IntStream.range(0, dtaArr.size())
        .filter(i -> dta.get(i).getRateUID().equals(rateUID))
        .findFirst();
英文:

Use IntStream.range:

OptionalInt idx =
    IntStream.range(0, dtaArr.size())
        .filter(i -&gt; dta.get(i).getRateUID().equals(rateUID))
        .findFirst();

huangapple
  • 本文由 发表于 2020年8月4日 16:56:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63243377.html
匿名

发表评论

匿名网友

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

确定