Tuesday, December 5, 2017

JAVA - How to use TreeMap

java.util.TreeMap is map with this behavior:
  • Keys can`t be duplicated.
  • Elements are sorted by keys.
TreeMap tr = new TreeMap();

/* -- add keys and it values */
    
tr.put( "one", 1 );
tr.put( "two", 2 );
tr.put( "three", 3 );
tr.put( "three", 5 ); // exists already -> ignore
tr.put( "three", 3 ); // exists already -> ignore
tr.put( "four", null ); 

/* elements count */
System.out.println( "Elements count = " + tr.size() );   

/* check if contains key */
System.out.println( "Contains \"one\" = " + tr.containsKey( "one" ) );   

/* get value for key */
System.out.println( "\"one\" value = " + tr.get( "two" ) );   
    
/* -- write all keys and all values */
        
System.out.println( "Keys = " + new ArrayList( tr.keySet() ).toString() );  
System.out.println( "Values = " + new ArrayList( tr.values() ).toString() );
Output:
Elements count = 4
Contains "one" = true
"one" value = 2
Keys = [four, one, three, two]
Values = [null, 1, 3, 2]
See that the order of elements are by the key name. Also count of elements is 4 - two items were omitted.

No comments:

Post a Comment