I’m a beginner in Java. I have a method as below:
public void time_filter(Long t1, Long t2){ NavigableMap<Long, Operations_enter> time_map = new TreeMap<Long, Operations_enter>(); for(int i=0; i< tm.size();i++){ Operations_enter op = new Operations_enter(); op.cpuid_enter = cpu.get(i); op.func_enter = stt.get(i); op.time_enter = tm.get(i); op.src_enter = tok.get(i); time_map.put(op.time_enter, op); } for(Map.Entry<Long, Operations_enter> entry: time_map.subMap(t1, true, t2, true).entrySet()){ Integer time_func = entry.getValue().func_enter; System.out.println(" Filtered function numbers corresponding to given time range is" + time_func); }
So like seen above, I implement a NavigableMap
with TreeMap
and Im able to filter for a given range using the subMap
method in NavigableMap. But I have a problem now, the time_enter
contains some duplicate keys, so when I use TreeMap
, the values get overwritten by the latest added duplicate value. I understand that it is how TreeMap
works. I tried using ConcurrentSkipListMap
too, but the result was the same.
What is the actual difference between ConcurrentSkipListMap
and TreeMap
?? And is there a possibility to implement NavigableMap
with either TreeMap
or ConcurrentSkipListMap
and at the same time have the duplicate values included in the NavigableMap
?
EDIT The code looks like this now:
NavigableMap<Long, Operations_enter> time_map = new TreeMap<Long, Operations_enter>(new Comparator<Long>() { public int compare(Long o1, Long o2) { return o1.equals(o2) ? 1 : o1.compareTo(o2); } }); for(int i=0; i< tm.size();i++){ Operations_enter op = new Operations_enter(); op.cpuid_enter = cpu.get(i); op.func_enter = stt.get(i); op.time_enter = tm.get(i); op.src_enter = tok.get(i); time_map.put(op.time_enter, op); } for(Map.Entry<Long, Operations_enter> entry: time_map.subMap(t1, true, t2, true).entrySet()){ Integer time_func = entry.getValue().func_enter; System.out.println(" Filtered function numbers corresponding to given time range is" + time_func); }
Advertisement
Answer
ConcurrentSkipListMap is a NavigableMap implementation designed to be safely used from multiple threads concurrently. This is its main difference from TreeMap. Since your time_map
is a local variable it can be accessed only from current thread and you dont need ConcurrentSkipListMap.
If you need a TreeMap that allows duplicate keys, you can try to make a custom Comparator that never returns 0:
TreeMap<Integer, Object> m = new TreeMap<>(new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o1.equals(o2) ? 1 : o1.compareTo(o2); } }); m.put(0, 0); m.put(1, 1); m.put(1, 1); m.put(1, 1); m.put(2, 2); m.put(3, 3); m.put(4, 4); System.out.println(m.subMap(0, false, 3, true));
output
{1=1, 1=1, 2=2, 3=3}
note that it breaks Map contract which may cause unexpected behavior eg m.containsKey(1) returns false instead you need to use m.subMap(0, false, 2, false) != null