Java / Programs
Write a Java program to find the first repeating character in a String.
The below program is implemented using Java 8.
public class FirstRepeatingChar { public static void main(String[] args) { String str = "abcdklha"; Set<Integer> myTempHashSet = new HashSet<>(); str.codePoints().filter(i -> myTempHashSet.add(i) == false).findFirst() .ifPresent(i -> System.out.println("First repeating Char: " + (char) i)); } }
Java7 version.
public class FirstRepeatingCharJava7 { public static void main(String[] args) { String str = "abcdklha"; Set<Character> myTempHashSet = new HashSet<>(); for (int i = 0; i < str.length(); i++) { if (myTempHashSet.add(str.charAt(i)) == false) { System.out.println("First repeating character: " + str.charAt(i)); break; } } } }
More Related questions...