Java Collections

Java Collections are one of most used classes and set of interfaces while programming in java. It provides apis to handle collection of objects. Java provides ready to use collection classes based on various data types. Besides Java we will discuss on using Google’s Guava and Apache Common’s Collection Library as well.

Iterable Interface

The Iterable interface (java.lang.interface) is one of the root interface of the Java Collection classes. The Collection interface extends Iterable so all the subtypes of Collections implements Iterable interface.

Collection Subtypes


/* Straight Java */
List<String> games = new ArrayList<String>();
games.add("Fifa 2017");
games.add("Uncharted 3");
games.add("Sim City 5");

/* Using Diamond Operator */
List<String> games = new ArrayList<>();
games.add("Mario Bro");
games.add("Duck Hunt");
games.add("Ninja Turtles");

/* Using Guava */
List<String> games = Lists.newArrayList("Soccer", "Basketball", "Tennis");

Accessing and Adding Elements

List listA = Lists.newArrayList();

//Adding Elements

//Accessing via Index
Sting element1 = listA.get(0);


//Iterating List (Using Lambda)
favoriteSongs.forEach(song->{"{} --> {}",song.toUpperCase(), countWords(song));

//Iterating (Simple)
for (String song: favoriteSongs) {;

//Iterating using fori
for (int i = 0; i < favoriteSongs.size(); i++) {;


//Sorting List
favoriteSongs.sort(new Comparator<String>() {
    @Override public int compare(String o1, String o2) {
        return o1.compareTo(o2);