HashMap function keyset () in java

HashMap<Character,Character> h=new HashMap<>();
for(int i=0; i<str.length(); i++){
    h.put(str.charAt(i),str.charAt(i));
}
Set<Character> keys=h.keySet();

Character [] arr=new Character[keys.size()];

keys.toArray(arr);
String ans="";
for(int i=0; i<arr.length; i++) {
    ans+=arr[i];
}

      

In this question, I have to remove duplicates from the entered string. It works fine for normal characters, but when the input is similar: o&6nQ0DT$3

for example containing special characters, then it is not printed in order.

input: o&6nQ0DT$3
expected output: o&6nQ0DT$3 
my output: 0Q3DT$&6no

      

I get the value returned by the method keyset()

in the set of "keys" (since the return type is set internally keyset()

), after that I created an array of length keys and put a string in it to return. But his arrival is in a different order.

+3


source to share


5 answers


A HashMap

(or HashSet

for that matter) has no intrinsic order. The fact that it worked for some materials is just a stroke of luck. You can use LinkedHashMap

as @javaguy suggests, or it might be easier to implement this whole exercise using streams:



String input =  "o&6nQ0DT$3";
String output = input.chars()
                     .distinct()
                     .mapToObj(c -> String.valueOf((char) c))
                     .collect(Collectors.joining());

      

+2


source


HashMap does not guarantee / preserves the order of insertion of elements, so use LinkedHashMap

to preserve the order of characters you insert:



Map<Character,Character> h = new LinkedHashMap<>();//use LinkedHashMap

      

+1


source


can this be done without a HashMap?

    String str = "Teste";
    String finalStr = ""; 

    for (Character charInString: str.toCharArray()) {
        if(!finalStr.contains(charInString.toString()))
        {
            finalStr += charInString;
        }

    }
    System.out.println(finalStr);

      

Improvement, how about this? A workaround with TreeSet .

    String str = "teste";
    HashMap<Integer, Character> map = new HashMap<>();
    for (int i = 0; i < str.length(); i++) {
        if (!map.containsValue(str.charAt(i))) {
            map.put(i, str.charAt(i));
        }
    }
    SortedSet<Integer> keys = new TreeSet<Integer>(map.keySet());
    keys.forEach(k -> System.out.println(k + " value " + map.get(k).toString()));

      

+1


source


LinkedHashMap and LinkedHashSet maintains insert order.

String s = "o&6nQ0DT$3";
Map<Character,Character> hm = new LinkedHashMap<>();    
for(Character c:s.toCharArray())
    hm.put(c, c);
System.out.println(hm);

      

Output:

{o=o, &=&, 6=6, n=n, Q=Q, 0=0, D=D, T=T, $=$, 3=3}

      

But LinkedHashSet uses hashmap internally to store values, so performance will be slightly better on LinkedHashMap.

+1


source


I don't see how you are using the hashmap completely, you might want to replace the ArrayList with this:

ArrayList<Character> h = new ArrayList<>();
for(int i=0;i<str.length();i++)
{
   if(!h.contains(str.charAt(i)))
      h.add(str.charAt(i));
   }
...

      

The Arrayalist will also keep the same insertion order.

0


source







All Articles