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

List

/* 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
listA.add("element1");

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

Iterating

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

//Iterating (Simple)
for (String song: favoriteSongs) {
    log.info(song.toLowerCase());
}

//Iterating using fori
for (int i = 0; i < favoriteSongs.size(); i++) {
    log.info(favoriteSongs.get(i).toUpperCase());
}

Sorting

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