Mega Code Archive

 
Categories / Java Tutorial / Collections
 

Headset, tailset and subset

headSet: The fromElement will be in the subset, while the toElement will not: fromElement If you want the toElement to be in the subset, you must pass in the next node of the tree, or a value that is just beyond the element. If you are using string nodes, you can adding something to the end: SortedSet headSet = set.headSet(toElement+"\0"); To remove the fromElement in the subset: SortedSet tailSet = set.tailSet(fromElement+"\0"); To get a set that includes both ends, use: SortedSet bothEnds = set.subSet(fromElement, toElement+"\0"); Or, for a set that includes neither end, use: SortedSet neitherEnd = set.subSet(fromElement+"\0", toElement); import java.util.Arrays; import java.util.TreeSet; public class MainClass {   public static void main(String args[]) throws Exception {     String elements[] = { "A", "C", "D", "G", "F" };     TreeSet set = new TreeSet(Arrays.asList(elements));     System.out.println(set.tailSet("C"));     System.out.println(set.headSet("C"));     System.out.println(set.headSet("C\0"));     System.out.println(set.tailSet("C\0"));     System.out.println(set.subSet("C", "F\0"));     System.out.println(set.subSet("C", "C\0"));     System.out.println(set.subSet("C", "C"));   } } [C, D, F, G] [A] [A, C] [D, F, G] [C, D, F] [C] [] While displaying elements in an easily sorted manner is nice, if you don't need the behavior, the cost to add elements and search for them is not worth it.