Jac*_* G. 19 java string java-8 java-stream java-9
给定一个String s和char c,我很好奇,如果存在制造的一些方法List<Integer> list从s(其中内的元素list表示的索引c内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());
}
Run Code Online (Sandbox Code Playgroud)
以下输入应产生以下输出:
getIndexList("Hello world!", 'l') -> [2, 3, 9]
Run Code Online (Sandbox Code Playgroud)
sma*_*c89 26
可以使用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());
}
Run Code Online (Sandbox Code Playgroud)
使用Java 9,您可以使用最后一个索引作为起始点进行迭代搜索,并在找不到匹配项时停止:
public static List<Integer> getIndexList(String s, char c) {
return IntStream.iterate(s.indexOf(c), i -> s.indexOf(c, i + 1))
.takeWhile(i -> i > -1)
.boxed()
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
免责声明:我没有测试过这个.
Java9中的替代方案可以是使用iterate(int seed, IntPredicate hasNext,IntUnaryOperator next)如下: -
private static List<Integer> getIndexList(String word, char c) {
return IntStream
.iterate(word.indexOf(c), index -> index >= 0, index -> word.indexOf(c, index + 1))
.boxed()
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
......或者在java-9中:
Stream.of("Hello world!")
.map(Scanner::new)
.flatMap(s -> s.findAll("l"))
.map(mr -> mr.start())
.forEach(System.out::println);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
902 次 |
| 最近记录: |