Java- Find first and all non-repeated characters from String
In Java, to find the first and all non-repeated characters from a string, you can use the following code:
NonRepeatedChar.java
package org.websparrow;
import java.util.ArrayList;
import java.util.List;
public class NonRepeatedChar {
public static void main(String[] args) {
String str = "websparrow";
firstNonRepeatedChar(str);
allNonRepeatedChar(str);
}
private static void firstNonRepeatedChar(String str) {
for (Character ch : str.toCharArray()) {
if (str.indexOf(ch) == str.lastIndexOf(ch)) {
System.out.println("First non-repeated character: " + ch);
break;
}
}
}
private static void allNonRepeatedChar(String str) {
List<Character> chars = new ArrayList<>();
for (Character ch : str.toCharArray()) {
if (str.indexOf(ch) == str.lastIndexOf(ch)) {
chars.add(ch);
}
}
System.out.println("All non-repeated character: " + chars);
}
}
Output:
First non-repeated character: e
All non-repeated character: [e, b, s, p, a, o]
References
- Java 8 – Find Non Duplicate Elements from List
- Find Non-Duplicate Elements from List in Python
- Java 8 – How to sort Set with stream.sorted()