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

  1. Java 8 – Find Non Duplicate Elements from List
  2. Find Non-Duplicate Elements from List in Python
  3. Java 8 – How to sort Set with stream.sorted()

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.