Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One approach to identifying the initial occurrence of both a repeated and an unrepeated character in a string would be to use the stream API and the characters() method to convert the string into a stream of characters. We can then use the collect() method with Collectors.groupingBy() to group the characters by their count, and then use the findFirst() method to find the initial occurrence of the characters we want.

Here's an example code that demonstrates this approach:

public static void main(String[] args) {
    String str = "hello world";
    Map<Integer, List<Character>> groupedChars = str.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(
                    c -> Collections.frequency(
                            str.chars().mapToObj(i -> (char) i).collect(Collectors.toList()), c)));

    Optional<Character> repeatedChar = groupedChars.getOrDefault(2, Collections.emptyList()).stream().findFirst();
    Optional<Character> unrepeatedChar = groupedChars.getOrDefault(1, Collections.emptyList()).stream().findFirst();

    System.out.println("Initial occurrence of repeated character: " + (repeatedChar.isPresent() ? str.indexOf(repeatedChar.get()) : "N/A"));
    System.out.println("Initial occurrence of unrepeated character: " + (unrepeatedChar.isPresent() ? str.indexOf(unrepeatedChar.get()) : "N/A"));
}

In this code, we first convert the string into a stream of characters using str.chars().mapToObj(c -> (char) c). We then group the characters by their count using Collectors.groupingBy(), and store the result in a map called groupedChars. To find the initial occurrence of the repeated character, we get the list of characters with a count of 2 from the groupedChars map, and call findFirst() on the resulting stream. We do the same to find the initial occurrence of the unrepeated character, but this time we get the list of characters with a count of 1.

Finally, we use the indexOf() method on the original string to find the index of the first occurrence of each character. If a character is not found, we print "N/A".