I have a list of words, 1000 words, I should list them from the most occurring to the least occurring.
Like:
Dog, 100 times
Cat, 50 times
Fish, 40 times
Monkey, 10 times
Bird, 10 times
Camel, 10 times
.
.
.
Lion, 1 times
Tiger, 1 times
I did this and works with a while loop, but it takes like 10 seconds, the next part of the task is to use Threads and make the sorting in less time. I plan on using 5 Threads, I can use them and run individually, say Thread1 can sort 1-200, Thread2 can sort 201-400, Thread3 can sort 401-600... but then in the end I would have 5 different lists? There would be 10 Dogs on Thread1 list, 20 Dogs in Thread2 list... Mixed up on console... I would like it to be as on above example using 5 Threads, is it possible? Could you please give some tips, I am new to Threads.
Edit: I'm using the built in sort functionality, for the time being it isn't important which sort algorithm I'm using. The task is not to use the best sorting algorithm but to sort with Threads.
Code:
//This is the list
ArrayList<String> animalList = new ArrayList<String>();
//This is the map from the list
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : animalList) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
//This is the final map
TreeMap<String, Integer> sortedMap = sortMapByValue(map);
public static TreeMap<String, Integer> sortMapByValue(Map<String, Integer> map){
Comparator<String> comparator = new ValueComparator(map);
TreeMap<String, Integer> result = new TreeMap<String, Integer>(comparator);
result.putAll(map);
return result;
}
public class ValueComparator implements Comparator<String>{
HashMap<String, Integer> map = new HashMap<String, Integer>();
public ValueComparator(Map<String, Integer> map2){
this.map.putAll(map2);
}
@Override
public int compare(String s1, String s2) {
if(map.get(s1) >= map.get(s2)){
return -1;
}else{
return 1;
}
}
}