Java program to Find the first non-repeating character from a stream of characters

JavaServer Side ProgrammingProgramming

To find the first non-repeating character from a stream of characters, the Java code is as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo{
   final static int max_chars = 256;
   static void non_repeating_char(){
      List<Character> my_list = new ArrayList<Character>();
      boolean[] repeat = new boolean[max_chars];
      String my_str = "Thisisasample";
      for (int i = 0; i < my_str.length(); i++){
         char x = my_str.charAt(i);
         if (!repeat[x]){
            if (!(my_list.contains(x))){
               my_list.add(x);
            }
            else{
               my_list.remove((Character)x);
               repeat[x] = true;
            }
         }
         if (my_list.size() != 0){
            System.out.print("The first non-repeating character of the string is ");
            System.out.println(my_list.get(0));
         }
      }
   }
   public static void main(String[] args){
      non_repeating_char();
   }
}

Output

The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T
The first non-repeating character of the string is T

A class named Demo contains a function named ‘non_repeating_char’ function. A list is created and a string is defined. This string is iterated over, and every character is inspected, and its count is stored in the form of a Boolean variable, in an array named ‘repeat’. The value will be true if it is repeated and false otherwise. In the main function, the function is called, and relevant message is displayed on the console.

raja
Published on 09-Jul-2020 06:38:37
Advertisements