In: Computer Science
import java.util.*;
import java.util.Map.Entry;
public class meso {
static String word;
//Parameterized constructor
public meso(String id) {
word=id;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
meso m = new meso("bdeca");
//Calling neou function to print characters in the string and returns hashmap
HashMap<Character, Integer> dict=neou(word);
//Calling another class
mesono m2 = new mesono(dict);
//Calling sortbykey function which is in mesono class
m2.sortbykey();
}
private static HashMap<Character, Integer> neou(String word2) {
// TODO Auto-generated method stub
HashMap<Character, Integer> hash =new HashMap<Character, Integer>();
System.out.println("Before sorting:");
//Reading each character in the string
for(int i=0;i<word2.length();i++) {
System.out.println(word2.charAt(i));
hash.put(word2.charAt(i), i);
}
return hash;
}
}
class mesono{
static HashMap<Character, Integer> map;
public mesono(HashMap<Character, Integer> dict) {
map=dict;
}
//Sorting values in the hashmap using treemap
public static void sortbykey()
{
// TreeMap to store values of HashMap
TreeMap<Character, Integer> sorted = new TreeMap<>();
// Copy all data from hashMap into TreeMap
sorted.putAll(map);
System.out.println("After sorting:");
// Display the TreeMap which is naturally sorted
for (Entry<Character, Integer> entry : sorted.entrySet())
System.out.println(entry.getKey());
}
}
Sample input and output:
Before sorting:
b
d
e
c
a
After sorting:
a
b
c
d
e
//Please leave comment if you have any doubts. THANK YOU.