I have a nested public class KeyCountMap
public KeyCountMap<T>
{
private IDictionary<T, MutableInt> map = new Dictionary<T, MutableInt>();
public KeyCountMap()
{ }
public KeyCountMap(Type dictionaryType)
{
if (!typeof(IDictionary<T, MutableInt>).IsAssignableFrom(dictionaryType))
{
throw new ArgumentException("Type must be a IDictionary<T, MutableInt>", "dictionaryType");
}
map = (IDictionary<T, MutableInt>)Activator.CreateInstance(_dictionaryType);
}
public HashSet<KeyValuePair<T, MutableInt>> EntrySet()
{
return map.ToSet();
}
//... rest of the methods...
}
To sort out the values in map in descending order of values, if we use Java we can write method as:
public static <T> KeyCountMap<T> sortMapByDescendValue(KeyCountMap<T> map)
{
List<Entry<T, MutableInt>> list = new LinkedList<>(map.entrySet());
Collections.sort(list, new Comparator<Entry<T, MutableInt>>()
{
@Override
public int compare(Entry<T, MutableInt> o1, Entry<T, MutableInt> o2)
{
return (-1) * (o1.getValue().get()).compareTo(o2.getValue().get());
}
});
KeyCountMap<T> result = new KeyCountMap<T>();
for (Entry<T, MutableInt> entry : list)
{
result.put(entry.getKey(), entry.getValue());
}
return result;
}
If we use C#, we can defined method as:
public static KeyCountMap<T> SortMapByDescendValue<T>(KeyCountMap<T> map)
{
List<KeyValuePair<T, MutableInt>> list = new List<KeyValuePair<T, MutableInt>>(map.EntrySet());
// map.EntrySet() returns of type HashSet<KeyValuePair<T, MutableInt>>
list = list.OrderByDescending(x => x.Value).ToList();
KeyCountMap<T> result = new KeyCountMap<T>();
foreach (KeyValuePair<T, MutableInt> entry in list)
{
result.Put(entry.Key, entry.Value);
}
return result;
}
Will this method work or is it necessary to override CompareTo()
method (not used here) for sorting?
EDIT
public class MutableInt
{
internal int _value = 1; // note that we start at 1 since we're counting
public void Increment()
{
_value++;
}
public void Discrement()
{
_value--;
}
public int Get()
{
return _value;
}
}
SortedDictionary<K,V>
– ClarkiaIDictionary
not aSortedDictionary
in classKeyCountMap<T>
– SavageSortedDictionary
instead ofIDictionary
in classKeyCountMap<T>
then is there any need to write a method like thatSortMapByDescendValue()
? – SavageSortedDictionary
it allows you to avoid sorting keys – SavageSortedDictionary<,>
, or a list if insertion order matters? WhyMutableInt
? If you provide a context, you'll most probably obtain better answers. As things are now, it seems you're trying to refurbish Java code to C# for no reason. – Burl