0

How to do I remove capital letters as well?

I have removed lower case duplicates but I cannot remove a duplicate if it is in upper case.

import java.util.HashMap;

public class HashMapDemo {

    public String removeDupes(String str){

        HashMap<Character, Integer> map = new HashMap<Character, Integer>();

        for(int i = 0; i < str.length(); i ++){
            char c = str.charAt(i);
            String s = String.valueOf(c);
            char d = (s.toUpperCase()).charAt(0);
            if(map.containsKey(c) || map.containsKey(d)){
                int count = map.get(c);
                map.put(c, count++);
            }
            else{
                map.put(c, 1);
            }
        }

        for(Character key : map.keySet()){
            int placeHolder = map.get(key);
            if(placeHolder != 1){
                map.remove(key);
            }
        }
        char[] placeHolder = new char[str.length()];
        int i = 0;
        for(Character key: map.keySet()){
            char var = key;
            placeHolder[i] = var;
            i++;
        }
        String lastWord = String.valueOf(placeHolder);

        return lastWord;
    }
}
  • 4
    Can you add a problem statement or description of what this code is supposed to be doing? – Tim Biegeleisen Oct 28 '17 at 13:29
  • Note: `Character.toUpperCase(c)` is an easier way to uppercase a char than converting it to a string. – Andy Turner Oct 28 '17 at 13:36
  • Also: you're going to get a `ConcurrentModificationException` in the loop where you remove keys. – Andy Turner Oct 28 '17 at 13:38
  • Why don't you use a LinkedHashSet ? See an example [here](https://stackoverflow.com/a/4989150/6252134). You'll just need to call `char[] chars = str.toLowerCase().toCharArray();` before. – Paul Lemarchand Oct 28 '17 at 13:40
  • You do `if(map.containsKey(c) || map.containsKey(d))` but then you do `map.get(c)`. What if map contains `d` but not `c`? NPE will be thrown here. – Vasan Oct 28 '17 at 13:41
  • I provided an answer to a similar question about finding things which occur only once here: https://stackoverflow.com/a/46981882/3788176 – Andy Turner Oct 28 '17 at 13:45

0 Answers0