Help the world stop coronavirus! Stay home!

Prev Next

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;
			}
		}
	}

}

❤Cash Back At Stores you Love !!!❤

Earn your $10 reward when you make your first purchase through Ebates by signing up with clicking below button.

Ebates Coupons and Cash Back

More Related questions...

Show more question and Answers...

JVM

Comments & Discussions