Map TreeMap key value pair sort by key, using of iterator Java Android example

Map TreeMap key value pair, Map sort by key, Iterator for Map Java Android example.

MainClass.java

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
 
public class MainClass {
	public static void main(String[] arg) {
 
		// english;germany dictionary
		String[] arrayOfString = { "one;eine", "two;zwei", "three;drei", "four;vier" };
 
		Map<String, String> map = new TreeMap<String, String>();
 
		for(String s: arrayOfString){
	    	String[] array = s.split(";");
	    	String sKey ="", sValue="";
	    	if(array.length > 1){
	    	sKey = array[0]; sValue = array[1];
	    		map.put(sKey, sValue);
	    	}
	    }
		List sortedByKeys=new ArrayList(map.keySet());
		Collections.sort(sortedByKeys);
 
            // iterate map
	    Set references = map.keySet();
	    Iterator it = references.iterator();
	    while (it.hasNext()) {
	      String key = (String) it.next();
	      String value = map.get(key);
	      System.out.println(key + " = " + value);
	    }
            // or other example how iterate map
	    TreeSet<String> keys = new TreeSet<String>(map.keySet());
	    for (String key : keys) { 
	       String value = map.get(key);
	       System.out.println(key + " = " + value);
 
	    }		
 
 
 
       // check if key exists 	    
//	   if( map.containsKey("two")){
//		System.out.print("two = " + map.get("two"));
//	   }
	}
}
/*
four = vier
one = eine
three = drei
two = zwei
 */
This entry was posted in Android Examples Code, Array,List,Collections and tagged , , , , , , , . Bookmark the permalink.


Comments are closed.

4,719 views