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

后端 未结 4 1688
抹茶落季
抹茶落季 2021-02-12 14:46

Given a String s and a char c, I\'m curious if there exists some method of producing a List list from s (where

4条回答
  •  别那么骄傲
    2021-02-12 15:27

    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 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.

提交回复
热议问题