Java 8/9:String中的字符是否可以映射到其索引(使用流)? [英] Java 8/9: Can a character in a String be mapped to its indices (using streams)?
本文介绍了Java 8/9:String中的字符是否可以映射到其索引(使用流)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
鉴于 String s
和 char c
,我很好奇是否存在某种生成方法列表与LT;整数> list
from s
(其中 list
中的元素代表<$ c $的索引c> c s
)。
Given a String s
and a char c
, I'm curious if there exists some method of producing a List<Integer> list
from s
(where the elements within list
represent the indices of c
within s
).
收盘,但不正确方法是:
public static List<Integer> getIndexList(String s, char c) {
return s.chars()
.mapToObj(i -> (char) i)
.filter(ch -> ch == c)
.map(s::indexOf) // Will obviously return the first index every time.
.collect(Collectors.toList());
}
以下输入应产生以下输出:
The following inputs should yield the following output:
getIndexList("Hello world!", 'l') -> [2, 3, 9]
推荐答案
可以用 IntStream
public static List<Integer> getIndexList(String s, char c) {
return IntStream.range(0, s.length())
.filter(index -> s.charAt(index) == c)
.boxed()
.collect(Collectors.toList());
}
这篇关于Java 8/9:String中的字符是否可以映射到其索引(使用流)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文