0% found this document useful (0 votes)
7 views

Java Repeated

java program Experience level question
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java Repeated

java program Experience level question
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

package com.demo.

main;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.function.Function;
import java.util.stream.Collectors;

public class FindFirstNonRepeatedCharacter {

public static void main(String[] args) {

String input = "helloHello";

String output = Arrays.stream(input.split(""))


.collect(Collectors.groupingBy(Function.identity(),
LinkedHashMap::new, Collectors.counting()))
.entrySet().stream().filter(e -> e.getValue() == 1)
.map(e -> e.getKey()).findFirst().get();
System.out.println("First non Repeated Character : " + output);
}
}

First we will split string based on “” empty string value


and will store into Array of string and after that we will
use Arrays.Stream(-) method and convert into stream
and after converting into stream we can
call .collect(-) method.Inside collect(-) method we can
pass the parameter Collectors.groupingBy(-,-) and
Inside Collectors.groupingBy(-,-) function we can pass
the two parameters one is Function.identity() to find the
unique identity of each element and second parameter we
can paas Collectors.counting() to count the number of
occurrence for each character. After that we again need to
convert Map into stream to apply stream functions. So we
can call .entrySet().stream() and now we can apply the
filter and restrict the data based on condition .filter(ele -
> ele.getValue() == 1) . Now we will store all the non
repeated keys into ArrayList and will pick the first non
repeated character and Print the output.

You might also like