logo
  • Programming
  • Testing
  • AI
  • Devops
  • Data Science
  • Design
  • Blogs
  • Crypto Tools
  • Dev Feed
  • Login
  • Donate
Story
Follow @devglan

Java Program to Find First non Repeated Character in a String

author-image   By Dhiraj Ray,   16 February, 2020 2K

Writing a Java program to find first non-repeated character in a String is a common programming interview question. For example, the first non-repeated character in the String 'devglan for developers' is 'g'.

This program can be used to test some advanced programming skills on usage of Collection framework in Java. The solution of this program can be built with a plain for-each loop by traversing each character of the String but we will be using in-built data structure called as LinkedHashMap and Java 8 stream operations to provide solution to this question.

LinkedHashMap is a Hash table and linked list implementation of the Map interface, with predictable iteration order meaning it maintains unique key and also the insertion order.

Below is the program implementation:

package com.devglan;

import java.util.LinkedHashMap;
import java.util.Map;

public class NonRepeatedCharacter {

    public static Character findNonRepeatedCharacters(String input){
        Character result = null;
        Map charactersMap = new LinkedHashMap<>();
        input.chars().mapToObj(i -> (char) i).forEach(character -> {
            if (!charactersMap.containsKey(character)) {
                charactersMap.put(character, 1);
            } else {
                charactersMap.put(character, charactersMap.get(character) + 1);
            }
        });

        Map.Entry filteredEntry = charactersMap.entrySet().stream().filter(entry -> entry.getValue() == 1).findFirst().orElse(null);
        if(filteredEntry != null){
            result = filteredEntry.getKey();
        }
        return result;
    }

    public static void main(String [] args){
        String input = "devglan for developers";
        Character nonRepeatedChar = findNonRepeatedCharacters(input);
        if(nonRepeatedChar != null) {
            System.out.println(String.format("First non repeated character for String %s is : %s", input, findNonRepeatedCharacters(input)));
        }else {
            System.out.println("No repeated characters found.");
        }
    }
}

Output : First non repeated character for String devglan for developers is : g

Explanation

Click to Suggest Your Own Explanation

As LinkedhashMap maintains unique key as well as inserton order, we will traverse the every character of the String and populate the Map with key as the character of the string and value as it's count. If the Map already contains the key, we will simply increase the count and at the end we will have each character as a key and it's count as value. Since, LinkedhashMap maintains insertion order, we will loop the Map and find the first key whose value is equal to 1. This key will be the first non repeated character in a String.

Other Similar Java Programs:

1 Java Program to test if given number is Armstrong or not
2 Java Program to test if a given number is Fibonacci or not
3 java program to find distinct word list from a file
4 Java program to find duplicate character from a string
5 Java Program to find middle index of array where both ends sum is equal
6 Java Program to find line with max character length in descending order in Java
7 Java Program to find max two numbers in an array
8 Java program to find max repeated words from a file
9 Java program to find sum of prime numbers
10 Java program to reverse a given number
11 Java program to find permutations of a given string
12 Java program to reverse a given string
13 Java program to find factorial of a given number
14 Java Program for Binary Search
15 Java Program to Add Two 2D Matrix
16 3 Ways to Check if Given Words are Anagram or not
17 Java Program to Find LCM of a Two Given Number
18 Check Given String is Rotation of Another String
19 Java Program To Check If A Given Number is A Perfect Number
20 Remove Common Characters From Given Strings
21 Find Second Largest Number in Array
22 Java Program To Find the Longest Palindrome Present in a String
23 Java Program to Reverse an Array in Place Without Using Any Second Array
24 Java Program to Print 1 To 10 Without Using Loop
25 Write a Java Program to Compare Files in Java
26 Java Program to Find missing Number in an Array
27 Write a Java Program to Find Union and Intersection of Arrays in Java
28 Writing a Java program to rotate an array by d elements.
29 Write a Java program to rotate a matrix
30 Write a Java program to find the largest sum of the contiguous subarray in a given Array

If You Appreciate This, You Can Consider:

  • Share this article on social media or with your teammates.

Suggest Explanation

The suggestion has been saved for review.Thanks for your effort.

{{errorMessage}}

Vertex

Devglan is one stop platform for all
programming tutorials and courses.

About Us

  • About Us
  • Contact Us
  • Submission Criteria
  • Privacy Policy

Quick Links

  • Home
  • Login / Join
  • Submit Your Story
  • Donate

Contact Us

Dhiraj
dhiraj@devglan.com

© 2021 Devglan. All rights reserved.