Sunday, 25 August 2013

Sorting Collection and Set

Sorting Collection and Set

I'm having an issue sorting the values and keys from a map from least to
greatest(integers and String's). Here are the two methods, first the
method for values:
public Collection<V> values(){
Collection<V> coll = new LinkedList<V>();
for(int i = 0; i < table.length; i++){
if(table[i] != null){
for(Entry<K, V> nextItem : table[i]){
if(nextItem.value != null){
if(!coll.contains(nextItem.value)){
coll.add(nextItem.value);
}
}
}
}
}
return coll;
}
Expected Output:
120 123 404 911 999
My Output (basically keeps order of wherever it was in the map):
911 999 123 120 404
The above method is used with dot notation for a hashTableChain (an array
who's keys are sorted by their hashCode where the indices of the array are
linkedLists), it returns the values for the given map. I tried sorting it
with Collections.sort(coll) however this requires a List which is
incompatible with Collection to my knowledge. Is there something
compatible with Collection that is either already sorted or can be sorted
in an easy way? The method for the key's:
public Set<K> keySet(){
Set<K> coll = new HashSet<K>();
for(int i = 0; i < table.length; i++){
if(table[i] != null){
for(Entry<K, V> nextItem : table[i]){
coll.add(nextItem.key);
}
}
}
return coll;
}
Expected Output:
ABC ACTG HTML LOL OMG XYZ
My Output (basically keeps order of wherever it was in the map):
XYZ ABC ACTG HTML LOL OMG
Again I tried Collections.sort(coll) to no avail and couldn't find any way
to sort it.
I'm fairly new to java and I'm sure I'm overlooking something, after
searching the web for a while I figured I'd just ask.
Thanks in advance and I very much appreciate the help.

No comments:

Post a Comment