Java Collection How to - Find messages from certain key till certain key








Question

We would like to know how to find messages from certain key till certain key.

Answer

import java.util.Collections;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;
// ww w .j  a  va2 s . c o  m
public class Main {
  public static void main(String[] args) {
    NavigableMap<Integer, String> nmap = new TreeMap<Integer, String>();
    nmap.put(1, "this");
    nmap.put(2, "is");
    nmap.put(3, "a");
    nmap.put(4, "test");
    nmap.put(5, ".");

    System.out.println(nmap);
    System.out.println(nmap.subMap(4, true, 5, true).values());
    nmap.subMap(1, true, 3, true).clear();
    System.out.println(nmap);
    // wrap into synchronized SortedMap
    SortedMap<Integer, String> ssmap = Collections.synchronizedSortedMap(nmap);

    System.out.println(ssmap.subMap(4, 5));
    System.out.println(ssmap.subMap(4, 5 + 1));
  }
}

The code above generates the following result.