Java 8/9: Can a character in a String be mapped to its indices (using streams)?

☆樱花仙子☆ 提交于 2019-12-03 09:57:42

Can be done with 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());
}

Using Java 9, you can iteratively search using the last index as the starting point, and stop when no match is found:

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());
}

Disclaimer: I didn't test this.

An alternate in Java9 could be to make use of the iterate(int seed, IntPredicate hasNext,IntUnaryOperator next) as follows:-

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());
}

...Or in java-9:

Stream.of("Hello world!")
            .map(Scanner::new)
            .flatMap(s -> s.findAll("l"))
            .map(mr -> mr.start())
            .forEach(System.out::println);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!