开发者

Sort Values in HashMap

开发者 https://www.devze.com 2023-04-05 18:25 出处:网络
You have two hashmaps HM1 and HM2 where key = Id(long) value = timestamp. You need to give开发者_JS百科 a program to return a list of Ids combined from both the hashmaps such that they are sorted as p

You have two hashmaps HM1 and HM2 where key = Id(long) value = timestamp. You need to give开发者_JS百科 a program to return a list of Ids combined from both the hashmaps such that they are sorted as per their timestamps.

My Solution: a. Wrap the object timestamp and id, in another object. Write a comparator on the basis of timestamp of the object, sort the list of objects and return the ids.

Any more intelligent way to do it?


Sounds like a perfectly reasonable way to go to me. You'll need to consider the situation where a single ID appears in both maps, but other than that it sounds very straightforward.

Note that you don't necessarily need to have a separate external comparator - you could make your new class implement Comparable<T> for itself. That would work equally well. For extra credit you could even potentially implement both solutions and compare and contrast them ;)


You could avoid wrapping into a new object type by doing the following:

    List<String> ids = new ArrayList<String>();

    List<String> keys = new ArrayList<String>(HM1.keySet());
    List<Double> values = new ArrayList<Double>(HM1.values());

    keys.add(HM2.keySet());
    values.add(HM2.values());

    TreeSet<Double> sortedSet = new TreeSet<Double>(values);
    Object[] sortedArray = sortedSet.toArray();
    for (int i=0; i < sortedArray.length; i++){
        ids.add(keys.get(values.indexOf(sortedArray[i])));
    }

    return ids;
0

精彩评论

暂无评论...
验证码 换一张
取 消