Search code examples
javahashmaptreemapmultimaplinkedhashset

How to sort by key in Java?


I have date in this format:

Key        Value 
13:00:08 : 3
13:00:08 : 2
13:00:08 : 2
13:00:06 : 2
13:00:08 : 2
13:00:09 : 1
13:00:07 : 2
13:00:09 : 3

I convert the timestamp to seconds. Then based on the timestamp, I have to sort the data.

I tried using TreeMap but it removes duplicates. I tried HashMap but it removes the duplicates. MultiMap will not work here.

Code which I tried was :

Map<Integer, Integer> map = new TreeMap<Integer, Integer>(tmap);
        System.out.println("After Sorting:");
        Set set2 = map.entrySet();
        Iterator iterator2 = set2.iterator();
        while(iterator2.hasNext()) {
            Map.Entry me2 = (Map.Entry)iterator2.next();
            System.out.print(me2.getKey() + ": ");
            System.out.println(me2.getValue());
        }

How can I proceed with the sorting?


Solution

  • Sounds like you just want a list.

    Encapsulate the time and the value in an object, and process a list of these objects. You can then sort the list by time.

    public class TimeValue {
        LocalTime time;
        int value;
    
        public TimeValue(LocalTime time, int value) {
            this.time = time;
            this.value = value;
        }
    
        public LocalTime getTime() {
            return time;
        }
    
        public static void main(String[] args) {
            List<TimeValue> timeValues = new ArrayList<>();
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 3));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 6), 2));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 8), 2));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 9), 1));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 7), 2));
            timeValues.add(new TimeValue(LocalTime.of(13, 0, 9), 3));
    
            timeValues.sort(Comparator.comparing(TimeValue::getTime));
    
            System.out.println(timeValues);
        }
    
        @Override
        public String toString() {
            return this.time + ": " + this.value;
        }
    }
    

    The reason why a List is preferable to a Map is that in your case the time is not unique; it can therefore not be used as a key.