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.
source to share
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());
source to share
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()));
source to share
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.
source to share
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.
source to share