Support free tutorials:











vogella training Training Books



Java Collections - Tutorial

Lars Vogel

Version 2.4

Revision History
Revision 0.1 - 2.4 07.08.2008 - 27.02.2014 Lars
Vogel
bug fixes and updates

Introduction to Java Collections

This tutorial explains the usage of the Java Collections, e.g. Lists, ArrayLists and Maps.


Table of Contents

1. Java Collections
1.1. What are collections
1.2. Important default implementations
1.3. Type information with Generics
2. Maps in Java
2.1. Map and HashMap
2.2. Convert keys in the Map to Array or ArrayList
3. Important implementations
3.1. Map and HashMap
3.2. Convert keys in the Map to Array or ArrayList
3.3. List, ArrayList and LinkedList
4. Useful collection methods
5. Using Collections.sort and Comparator in Java
6. Exercise: Use Java Collections
7. Support this website
7.1. Thank you
7.2. Questions and Discussion
8. Links and Literature

1. Java Collections

1.1. What are collections

The Java language supports arrays to store data. Arrays are of a fixed size which is defined during initialization of the array.

Developer typically require a data structure which is flexible in size, so that they can add and remove items from this data structure on request. To avoid that every developer has to implement his custom data structure the Java library provide several default implementations for this via the collection framework.

Java collections are dynamic in size, e.g. a collection can contain a flexible number of objects.

Tip

Collections are implemented based on arrays. See for example Implementing an ArrayList in Java for and example how to implement a list based on arrays.

More theoretical said, collection is a data structure which contains and processes a set of data. The data stored in the collection is encapsulated and the access to the data is only possible via predefined methods.

For example if your application saves data in an object of type People, you can store several People objects in a collection.

1.2. Important default implementations

Typical collections are: stacks, queues, deques, lists and trees.

1.3. Type information with Generics

As of Java 5 collections should get parameterized with an object declaration to enable the compiler to check if objects which are added to the collection have the correct type. This is based on Generics. Generics allow a type or method to operate on objects of various types while providing compile-time type safety.

The following code shows an example how to create a Collection of type List which is parameterized with <String> to indicate to the Java compiler that only Strings are allowed in this list. .

package collections;

import java.util.ArrayList;

public class MyArrayList {

    public static void main(String[] args) {

      // create a list, use is ArrayList as concrete type 
      // ArrayList<> infers the String type from the left side
        List<String> var = new ArrayList<>();
        
        // add a few Strings to it
        var.add("Lars");
        var.add("Tom");
        
        // Loop over it and print the result to the console
        for (String s : var) {
            System.out.println(s);
        }
    }
} 

If you try to put a non String into this list, you would receive a compiler error.

List is only an interface, a common implementation is the ArrayList class, hence you need to call new ArrayList().

2. Maps in Java

2.1. Map and HashMap

The Map interface defines an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

The HashMap class is an efficient implementation of the Map interface. The following code demonstrates its usage.

package com.vogella.java.collections.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapTester {
  public static void main(String[] args) {
    
    // keys are Strings
    // objects are also Strings
    Map<String, String> map = new HashMap<>();
    fillData(map);

    // write to command line
    for (String key : map.keySet()) {
      System.out.println(key + " " + map.get(key));
    }

    // add and remove from the map
    map.put("iPhone", "Created by Apple");
    map.remove("Android");

    // write again to command line
    for (String key : map.keySet()) {
      System.out.println(key + " " + map.get(key));
    }
  }

  private static void fillData(Map<String, String> map) {
    map.put("Android", "Mobile");
    map.put("Eclipse IDE", "Java");
    map.put("Eclipse RCP", "Java");
    map.put("Git", "Version control system");
    
  } 

2.2. Convert keys in the Map to Array or ArrayList

You can convert your keys or values to an array or list. The following code demonstrates that.

package com.vogella.java.collections.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConvertMapTester {
  public static void main(String[] args) {
    
    // keys are Strings
    // objects are also Strings
    Map<String, String> map = new HashMap<>();
    fillData(map);
    
    // convert keys to array
    String[] strings = keysAsArray(map);
    for (String string : strings) {
      System.out.println(string);
    }
    // convert keys to list
    List<String> list = keysAsList(map);
    for (String string : list) {
      System.out.println(string);
    }
  }

  private static void fillData(Map<String, String> map) {
    map.put("Android", "Mobile");
    map.put("Eclipse IDE", "Java");
    map.put("Eclipse RCP", "Java");
    map.put("Git", "Version control system");
    
  }

  private static String[] keysAsArray(Map<String, String> map) {
    return map.keySet().toArray(new String[map.keySet().size()]);
  }

  // assumes the key is of type String
  private static List<String> keysAsList(Map<String, String> map) {
    List<String> list = new ArrayList<String>(map.keySet());
    return list;
  }

} 

3. Important implementations

3.1. Map and HashMap

The Map interface defines an object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

The HashMap class is an efficient implementation of the Map interface. The following code demonstrates its usage.

package com.vogella.java.collections.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapTester {
  public static void main(String[] args) {
    
    // keys are Strings
    // objects are also Strings
    Map<String, String> map = new HashMap<>();
    fillData(map);

    // write to command line
    for (String key : map.keySet()) {
      System.out.println(key + " " + map.get(key));
    }

    // add and remove from the map
    map.put("iPhone", "Created by Apple");
    map.remove("Android");

    // write again to command line
    for (String key : map.keySet()) {
      System.out.println(key + " " + map.get(key));
    }
  }

  private static void fillData(Map<String, String> map) {
    map.put("Android", "Mobile");
    map.put("Eclipse IDE", "Java");
    map.put("Eclipse RCP", "Java");
    map.put("Git", "Version control system");
    
  } 

3.2. Convert keys in the Map to Array or ArrayList

You can convert your keys or values to an array or list. The following code demonstrates that.

package com.vogella.java.collections.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConvertMapTester {
  public static void main(String[] args) {
    
    // keys are Strings
    // objects are also Strings
    Map<String, String> map = new HashMap<>();
    fillData(map);
    
    // convert keys to array
    String[] strings = keysAsArray(map);
    for (String string : strings) {
      System.out.println(string);
    }
    // convert keys to list
    List<String> list = keysAsList(map);
    for (String string : list) {
      System.out.println(string);
    }
  }

  private static void fillData(Map<String, String> map) {
    map.put("Android", "Mobile");
    map.put("Eclipse IDE", "Java");
    map.put("Eclipse RCP", "Java");
    map.put("Git", "Version control system");
    
  }

  private static String[] keysAsArray(Map<String, String> map) {
    return map.keySet().toArray(new String[map.keySet().size()]);
  }

  // assumes the key is of type String
  private static List<String> keysAsList(Map<String, String> map) {
    List<String> list = new ArrayList<String>(map.keySet());
    return list;
  }

} 

3.3. List, ArrayList and LinkedList

List is the interface which allows to store objects in a resizable container.

ArrayList is implemented as a resizable array. If more elements are added to ArrayList than its initial size, its size is increased dynamically. The elements in an ArrayList can be accessed directly and efficiently by using the get() and get() methods, since ArrayList is implemented based on an array.

LinkedList is implemented as a double linked list. Its performance on add() and remove() is better than the performance of Arraylist. The get() and get() methods have worse performance than the ArrayList, as the LinkedList does not provide direct access.

The following code demonstrates the usage of List and ArrayList.

package com.vogella.java.collections.list;

import java.util.ArrayList;
import java.util.List;

public class ListExample {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(3);
    list.add(2);
    list.add(1);
    list.add(4);
    list.add(5);
    list.add(6);
    list.add(6);
    for (Integer integer : list) {
      System.out.println(integer);
    }
  }

} 

4. Useful collection methods

The java.util.Collections class provides useful functionalities for working with collections.

Table 1. Collections

Method Description
Collections.copy(list, list) Copy a collection to another
Collections.reverse(list) Reverse the order of the list
Collections.shuffle(list) Shuffle the list
Collections.sort(list) Sort the list

5. Using Collections.sort and Comparator in Java

Sorting a collection in Java is easy, just use the Collections.sort(Collection) to sort your values. The following code shows an example for this.

package de.vogella.algorithms.sort.standardjava;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Simple {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(5);
        list.add(4);
        list.add(3);
        list.add(7);
        list.add(2);
        list.add(1);
        Collections.sort(list);
        for (Integer integer : list) {
            System.out.println(integer);
        }
    }
} 

This is possible because Integer implements the Comparable interface. This interface defines the method compare which performs pairwise comparison of the elements and returns -1 if the element is smaller then the compared element, 0 if it is equal and 1 if it is larger.

If what to sort differently you can define your own implementation based on the Comparator interface.

package de.vogella.algorithms.sort.standardjava;
 
import java.util.Comparator;
 
public class MyIntComparable implements Comparator<Integer>{
 
    @Override
    public int compare(Integer o1, Integer o2) {
        return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
    }
} 

package de.vogella.algorithms.sort.standardjava;

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

public class Simple2 {
  public static void main(String[] args) {
    List<Integer> list = new ArrayList<Integer>();
    list.add(5);
    list.add(4);
    list.add(3);
    list.add(7);
    list.add(2);
    list.add(1);
    Collections.sort(list, new MyIntComparable());
    for (Integer integer : list) {
      System.out.println(integer);
    }
  }

} 

Note

For the above you could also have used the Collection.reverse() method call.

This approach is that you then sort any object by any attribute or even a combination of attributes. For example if you have objects of type Person with an attribute income and dataOfBirth you could define different implementations of Comparator and sort the objects according to your needs.

6. Exercise: Use Java Collections

Create a new Java project called com.vogella.java.collections. Also add a package with the same name.

Create a Java class called Server with one String attribute called url.

package com.vogella.java.collections;

public class Server {
    private String url;
} 

Create getter and setter methods for this attribute using code generation capabilities of Eclipse. For this select SourceGenerate Getters and Setters from the Eclipse menu.

Create via Eclipse a constructor which gets a url as parameter. For this select SourceGenerate Constructor using Fields... from the Eclipse menu.

Type main in the class body and use code completion (Ctrl+Space) to generate a main method.

Code completion

In your main method create a List of type ArrayList and add 3 objects of type Server objects to this list.

public static void main(String[] args) {
    List<Server> list = new ArrayList<Server>();
    list.add(new Server("http://www.vogella.com"));
    list.add(new Server("http://www.google.com"));
    list.add(new Server("http://www.heise.de"));
} 

Use code completion to create a foreach loop and write the toString method to the console. Use code completion based on syso for that.

Run your program.

Use Eclipse to create a toString method based on the url parameter and re-run your program again.

7. Support this website

This tutorial is Open Content under the CC BY-NC-SA 3.0 DE license. Source code in this tutorial is distributed under the Eclipse Public License. See the vogella License page for details on the terms of reuse.

Writing and updating these tutorials is a lot of work. If this free community service was helpful, you can support the cause by giving a tip as well as reporting typos and factual errors.

7.1. Thank you

Please consider a contribution if this article helped you.

Flattr this

7.2. Questions and Discussion

If you find errors in this tutorial, please notify me (see the top of the page). Please note that due to the high volume of feedback I receive, I cannot answer questions to your implementation. Ensure you have read the vogella FAQ as I don't respond to questions already answered there.

8. Links and Literature

http://java.sun.com/docs/codeconv/index.html - Sun Coding Convention.