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]
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.
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.
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.
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.
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With