-2

I am having hard time in solving this question using java 8. I am aware of the similar question asked here. But that solution is not working as it returns "a" as first repeated character for below given input. The expected output is "e".

pls help.

Given input = "I am feeling happy";
Expected output = "e"

2 Answers 2

1

First of all, there is no technical reason to use Java 8 streams. The real purpose of Java 8 streams is to make code more concise and easier to read / understand. If you don't understand streams well enough ... or the problem is ill-suited to streams ... then you don't achieve that goal by using streams.

But assuming that you want to try, here is >a< solution.

import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        String input = "Feel the need";
        Set<Integer> seen = new HashSet<>();
        OptionalInt first = input.chars()
            .filter(i -> !seen.add(i))
            .findFirst();
        if (first.isPresent()) {
            System.out.println((char) first.getAsInt());
        }
    }
}

Explanation:

  1. String.chars() gives an IntStream ... !!
  2. Set.add returns false if the element was already in the set.
  3. So ... filter(i -> !seen.add(i)) is filtering out characters that were not in seen; i.e. ones that aren't duplicate.
  4. The first() gives us the first duplicate ... or an empty optional.
  5. We need to cast the resulting int to a char to print it as a character.

Note: this is rather "dirty" because it depends on performing a side-effect on seen. It will break if you attempt to parallelize the stream. Also, we really should be streaming Unicode codepoints rather than char values.


In fact the expected output from your question should be a space character, because SP is the first repeated character in the string!

0
1

Although you asked about a stream based solution, I believe that requirement is a symptom of an XY problem, because it can be done without a stream in one line:

String firstRepeated = str.replaceAll(".*?(.)(?=\\1).*|.*", "$1");

which returns the first repeated char, or the blank string if there is no repeated character.

Not the answer you're looking for? Browse other questions tagged or ask your own question.