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

后端 未结 4 1686
抹茶落季
抹茶落季 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

    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());
    }
    
    0 讨论(0)
  • 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<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.

    0 讨论(0)
  • 2021-02-12 15:33

    ...Or in java-9:

    Stream.of("Hello world!")
                .map(Scanner::new)
                .flatMap(s -> s.findAll("l"))
                .map(mr -> mr.start())
                .forEach(System.out::println);
    
    0 讨论(0)
  • 2021-02-12 15:35

    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());
    }
    
    0 讨论(0)
提交回复
热议问题