在Java中获取满足特定条件的数组的所有索引。

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

Get all indexes of an array with a certain condition in java

问题

我有一个字符串列表,我想将数组中所有字符串不为空的索引添加到一个集合中,

我尝试过这样做:

columnNum.addAll((Collection<? extends Integer>) IntStream.range(0, row.size()).filter(i -> StringUtils.isNotEmpty(row.get(i))));

但是我收到了一个异常。

英文:

I have a list of strings and I want to add to a set all indexes from array where the string is not empty,

I tried doing this:

columnNum.addAll((Collection&lt;? extends Integer&gt;) IntStream.range(0, row.size()).filter(i-&gt; StringUtils.isNotEmpty(row.get(i))));

but I get an exception

答案1

得分: 1

你需要使用包装类型:

var list = List.of("", "a", "", "b");

var set = IntStream.range(0, list.size())
        .filter(i -> !list.get(i).isEmpty()).boxed().collect(Collectors.toSet());
英文:

You have to use boxed:

var list = List.of(&quot;&quot;,&quot;a&quot;,&quot;&quot;,&quot;b&quot;);

var set = IntStream.range(0, list.size())
        .filter(i -&gt; 
   !list.get(i).isEmpty()).boxed().collect(Collectors.toSet());

答案2

得分: 0

Collect the stream to a List first. An IntStream is not a Collection.

columnNum.addAll(IntStream.range(0, row.size())
    .filter(i-> StringUtils.isNotEmpty(row.get(i)))
    .boxed().collect(Collectors.toList())); // or .toList() with Java 16+
英文:

Collect the stream to a List first. An IntStream is not a Collection.

columnNum.addAll(IntStream.range(0, row.size())
    .filter(i-&gt; StringUtils.isNotEmpty(row.get(i)))
	.boxed().collect(Collectors.toList())); // or .toList() with Java 16+

huangapple
  • 本文由 发表于 2023年2月8日 22:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75387610.html
匿名

发表评论

匿名网友

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

确定