Java (List & Map) – Create, Populate, Iterate & Sort

java-logoJava java.util.List & java.util.Map are highly used data structure, here we will see how to create, populate, iterate and sort objects of these types.

Objectives:

  • How to “create” “initialize” make new List & Map in Java?
  • How to “populate” add to List & Map?
  • How to Iterate over each item in List and entry in Map?
  • How to sort List & Map “by key & values”?
  • How to convert Map to List?

We will be using the following simple class “POJO” in our example.

  • Person.java
package com.hmkcode.vo;

public class Person {

	private int age;
	private String name;

	public Person(String name, int age){
		this.name = name;
		this.age = age;
	}

//getters & setters...
}

( 1 ) java.util.List “LinkedList & ArrayList”

java.util.List is an interface, it has more that one implementations. LinkedList & ArrayList are common ones.

  • Create new List
List<Person> arrayList = new ArrayList<Person>();
List<Person> linkedList = new LinkedList<Person>();
  • Populate List
arrayList.add(new Person());
linkedList.add(new Person());
  • Iterate List

We have two ways to iterate over a List the second one is more efficient way.

for(int i = 0; i < linkedList.size(); i++){
      System.out.println("LinkedList[ "+i+"]"+linkedList.get(i));       	
}

//this is an efficient way to iterate
for(Person person:linkedList){
	System.out.println("LinkedList: "+person);
}
  • Sort List

The object stored in list e.g. “Person” should implement Comparable interface in order to sort the list using Collections.sort()

package com.hmkcode.vo;

public class Person implements Comparable<Person> {

        // properties, getters, setters & constructor....
	@Override
	public int compareTo(Person person) {
		return this.age-person.getAge();
	}

}
Collections.sort(linkedList);

Complete Example:

package com.hmkcode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

import com.hmkcode.vo.Person;

public class ListApp 
{

    public static void main( String[] args )
    {

        // ( 1 ) List

        // A. Initiate
        List<Person> arrayList = new ArrayList<Person>();
        List<Person> linkedList = new LinkedList<Person>();

        // B. Populate
        for(Person person:getPersons()){
        	arrayList.add(person);
        	linkedList.add(person);
        }

        // --> print
        System.out.println("--------- Print All -------------");

        System.out.println("ArrayList: "+arrayList);
        System.out.println("LinkedList: "+linkedList);

        // C. Iterate
        System.out.println("--------- Print Iterate by index -------------");

        for(int i = 0; i < linkedList.size(); i++){
        	System.out.println("LinkedList[ "+i+" ]"+linkedList.get(i));        	
        }

        System.out.println("--------- Print Iterate by for each -------------");

        //this is an efficient way to iterate
        for(Person person:linkedList){
        	System.out.println("LinkedList: "+person);
        }

        // D. Sort
        Collections.sort(linkedList);

        // --> print
        System.out.println("--------- Print Sorted List -------------");

        System.out.println("Sorted LinkedList: "+linkedList);
    }

    private static Person[] getPersons(){
    	Person[] persons = new Person[5];

    	persons[0] = new Person("Brit", 29);
    	persons[1] = new Person("John", 32);
    	persons[2] = new Person("Jack", 27);
    	persons[3] = new Person("Jenifer", 24);
    	persons[4] = new Person("Brit", 37);

    	return persons;
    }
}

( 2 ) java.util.Map “HashMap & TreeMap”

  • Create new Map
Map<String,Person> hashMap = new HashMap<String,Person>();
Map<String,Person> treeMap = new TreeMap<String,Person>();
  • Populate Map

If we insert more than one entry, TreeMap will keep the insertion order!

hashMap.put("key",new Person());
treeMap.put("key",new Person());
  • Iterate Map

We have two ways:

1st way is to get keys then we get value by calling map.get(key)

for(String key:treeMap.keySet()){

System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key));

}

2nd way is to get Map.Entry which is each record in the map one by one.

 for(Entry<String, Person> entry:treeMap.entrySet()){

System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue());
        }
  • Sort Map

The result of the sort need to be stored in a TreeMap to keep the order.

  TreeMap<String,Person> sorted_map = new TreeMap<String,Person>(new ValueComparator());
        sorted_map.putAll(hashMap);

We need to define a comparator to compare key objects.

class ValueComparator implements Comparator {

	  Map map;

	  public ValueComparator(){

	  }
	  public int compare(Object keyA, Object keyB){

	  	return ((String) keyA).compareTo((String) keyB);

	  }
}
  • Converting Map to List

If we want to extract map values in a list we can do it as following:

 List<Person> persons = new ArrayList<Person>(sorted_map.values());

Complete Example:

package com.hmkcode;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import com.hmkcode.vo.Person;

public class MapApp 
{

    public static void main( String[] args )
    {

        // ( 1 ) Map

        // A. Initiate
        Map<String,Person> hashMap = new HashMap<String,Person>();
        Map<String,Person> treeMap = new TreeMap<String,Person>();

        // B. Populate
        int k = 0 ;
        for(Person person:getPersons()){
        	hashMap.put(""+k,person);
        	treeMap.put(""+k++,person);
        }

        // --> print
        System.out.println("--------- Print All -------------");      
        System.out.println("HashMap: "+hashMap);
        System.out.println("TreeMap: "+treeMap);

        // C. Iterate
        // --> print
    	System.out.println("--------- Print Iterate by get(key) -------------");     
        for(String key:treeMap.keySet()){

        	System.out.println("treeMap: [key: "+key+" , value: "+treeMap.get(key));
        }
        // --> print
    	System.out.println("--------- Print Iterate by Entry -------------");  
        for(Entry<String, Person> entry:treeMap.entrySet()){

        	System.out.println("treeMap: [key: "+entry.getKey()+" , value: "+entry.getValue());
        }   

        // D. Sort by value
        TreeMap<String,Person> sorted_map = new TreeMap<String,Person>(new ValueComparator());
        sorted_map.putAll(hashMap);

        // --> print
        System.out.println("--------- Print Sorted Map by Value -------------");       
        System.out.println("Sorted HashMap: "+sorted_map);

        // E. Convert Map to List

        List<Person> persons = new ArrayList<Person>(sorted_map.values());

        // --> print
        System.out.println("--------- Print List<Person> -------------");
        System.out.println("List<Person>: "+persons);
    }

    private static Person[] getPersons(){
    	Person[] persons = new Person[5];

    	persons[0] = new Person("Brit", 29);
    	persons[1] = new Person("John", 32);
    	persons[2] = new Person("Jack", 27);
    	persons[3] = new Person("Jenifer", 24);
    	persons[4] = new Person("Brit", 37);

    	return persons;
    }
}
class ValueComparator implements Comparator {

	  Map map;

	  public ValueComparator(){

	  }
	  public int compare(Object keyA, Object keyB){

	  	return ((String) keyA).compareTo((String) keyB);

	  }
}

Source Code @ GitHub