Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

A close, but incorrect approach would be:

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]
like image 342
Jacob G. Avatar asked Feb 02 '18 23:02

Jacob G.


People also ask

How do you index a character in a String in Java?

You can get the character at a particular index within a string by invoking the charAt() accessor method. The index of the first character is 0, while the index of the last character is length()-1 . For example, the following code gets the character at index 9 in a string: String anotherPalindrome = "Niagara.

Can we use stream on String in Java?

Conversion Using chars()The String API has a new method – chars() – with which we can obtain an instance of Stream from a String object. This simple API returns an instance of IntStream from the input String.

Can we use map stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another. Let's see method signature of Stream's map method.

Can we use stream for map in Java?

Stream map() in Java with examplesStream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream. Stream map(Function mapper) is an intermediate operation.


1 Answers

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());
}
like image 151
smac89 Avatar answered Oct 12 '22 13:10

smac89