1

You have two hashmaps HM1 and HM2 where key = Id(long) value = timestamp. You need to give 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?

1
  • 1
    Your approach is correct. If you don't want to define a class you can create an ArrayList of Map.Key which works quite well as a Pair Commented Sep 19, 2011 at 18:11

2 Answers 2

1

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 ;)

Sign up to request clarification or add additional context in comments.

2 Comments

Why does he need any extra consideration for duplicate ID in the two maps? If the timestamp is different in the two then they would obviously be two different entries. If the timestamp is same, he may need a clarification whether they have to be listed twice.
@Hemal: They may be obviously different entries - but what would that mean in the real world? For example, it could indicate that the data is invalid, or that the second entry "overrides" the first one. It's the sort of thing which is easily forgotten but should be considered - the question of the correct behaviour should at least be asked.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.