John
John

Reputation: 1220

Figuring out the character value in finding first non repeated character in a string

I am working on finding first non repeating character in a String which is as follows:

package com.tk.practice;

import java.util.HashMap;
import java.util.Map;

public class FirstNonRepeatedCharacter {

public static void main(String[] args) {


        String str = "stress";

        char[] ch = str.toCharArray();

        int length = ch.length;
        //System.out.println(length);
        for(int i = 0; i<length;i++){
                char character = str.charAt(i); 
                Map<Character, Integer> map = new HashMap<Character,Integer>();
                if(map.containsKey(character)){
                    map.put(character, map.get(character)+1);
                }
                else{
                    map.put(character, 1);
                }

                for(Map.Entry<Character, Integer> m : map.entrySet()){
                            //Integer ill = m.getValue();
                            //Character ch1 = m.getKey();
                            //if(ill == 1){

                                System.out.println("Key: "+m.getKey()+" Value: "+m.getValue());

                            //}


       }




}

}}

It's just printing value one for each character right now. But I am trying to understand one thing in the following line:

if(map.containsKey(character)){
                        map.put(character, map.get(character)+1);
                    }

Since, the value is an integer value, then why map.get(character) isn't throwing any error as map.get(character) should be retrieving the character, right and not the value? I was thinking of using getKey() but that throws error. Please explain me if I have misunderstood something.

Upvotes: 0

Views: 28

Answers (1)

Heman Gandhi
Heman Gandhi

Reputation: 1371

Map.get returns an Integer since that's what the values in your map are. getKey will return a Character and get will return an Integer since the keys in your map are characters and the values are integers. get gives you the value at the key you provide.

Upvotes: 1

Related Questions