I used the below example code only to illustrate the problem with Java 8 stream API. I am not expecting workaround to the given code but the explanation why accumulator function is not possible/provided in Stream.
I want to get the first recurring character in a string without using the intermediate terminal operation or shared mutation using Java 8 Stream api. I can do this with RxJava scan operator without pain. The Scan/accumulator basically enable me to get hold of the previous element in the stream and I would be able to return my own type as the previous element from the scan. I see there are no possibilities with Java 8 stream but wanted to know why? What is the problem in implementing the scan/accumulator operation in Stream?
Issues with the workaround to achieve this:
If I use the terminal operation then all of my inputs are processed which is unnecessary
If I use mutation the code cannot be parallelized or bring more issues if someone uses stream.parallel.
given - String str = "rtydydret";
output - y - because y is the first repeating character in the string.
Imperative example to achieve this: -
List<Character> list = new ArrayList<>();
for (char charecter : str.toCharArray()) {
if (list.contains(charecter)) {
System.out.println(charecter);
break;
} else {
list.add(charecter);
}
}
I also do not want to use below code as it uses terminal operation which means it processed all the character in the string, that's bad.
Map<Character, Long> collect = "abcsdnvs".chars().mapToObj(i -> (char)i).collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
collect.forEach( (x,y) -> System.out.println( "Key: " + x + " Val: " + y));
Optional<Character> firstRepeat = collect.entrySet().stream().filter( (e) -> e.getValue() > 1).map(e -> e.getKey()).findFirst();
System.out.println("First repeating:" + firstRepeat.orElse(null));
Any insight would be greatly helpful. Thanks.