英文:
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<? extends Integer>) IntStream.range(0, row.size()).filter(i-> 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("","a","","b");
var set = IntStream.range(0, list.size())
.filter(i ->
!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-> StringUtils.isNotEmpty(row.get(i)))
.boxed().collect(Collectors.toList())); // or .toList() with Java 16+
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论