Find first repeated character in a string
Categories: Java 8(JDK1.8) Java Examples
package r4r.co.in;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class FindFirstRepeatedCharacter {
public static void main(String[] args) {
// Find first repeated character in a string
String str = "rajesh kumar";
Map<String, Long> map = Stream.of(str.split("")).filter(Objects::nonNull)
.collect(Collectors.groupingBy(Function.identity(), LinkedHashMap::new, Collectors.counting()));
System.out.println(map);
Entry<String, Long> entry = map.entrySet().stream().filter(s -> s.getValue() > 1).findFirst().orElse(null);
System.out.println(entry.getKey());
}
package r4r.co.in;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class FindFirstRepeatedCharacterInAString {
public static void main(String[] args) {
// Find first repeated character in a string
String str="rajesh kumar";
List<String> list= Arrays.asList(str.split(""));
String s=list.stream().filter(f->Collections.frequency(list,f)>1).findFirst().orElse(null);
System.out.println(s);
}
}
----------------------------------------------
package r4r.co.in;
import java.util.Collections;
import java.util.List;
public class FindFirstRepeatedCharacterInAString {
public static void main(String[] args) {
// Find first repeated character in a string
String str="rajesh kumar";
List<Character> intStream= str.chars().mapToObj(c->(char)c).toList();
Character s=intStream.stream().filter(f->Collections.frequency(intStream,f)>1).findFirst().orElse(null);
System.out.println(s);
}
}