Convert List to Map using Google Guava in Java

Here is a simple example that shows conversion of a List (java.util.List) to Map (java.util.Map) using Google’s Guava API.

Other Google Guava examples:
Iterables Find Example
Iterables Any Example
Better null checks using Optional Example
Convert Map to String


package com.idodevjobs;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

public class GoogleGuavaListToMap {

    private String input;

    public GoogleGuavaListToMap(String input) {
        this.input = input;
    }

    public static void main(String[] args) {

        List yourList = Lists.newArrayList(new GoogleGuavaListToMap("input1"), new GoogleGuavaListToMap("input2"));

        Map newMap = Maps.uniqueIndex(yourList, new Function<GoogleGuavaListToMap, String>() {
            @Override
            public String apply(GoogleGuavaListToMap googleGuavaListToMap) {
                return googleGuavaListToMap.getInput(); // or something else
            }
        });

        System.out.println(newMap);
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    @Override
    public String toString() {
        return "GoogleGuavaExample{" +
                "input='" + input + '\'' +
                '}';
    }
}

In this example, we are iterating through the List for unique objects and creating key-value pairs using the contents of the List to eventually create a map.

Leave comments should you have any questions.

This entry was posted in java and tagged , . Bookmark the permalink.

4 Responses to Convert List to Map using Google Guava in Java

  1. Pingback: Google Guava Iterables Find Example | iDoDevJobs

  2. Pingback: Google Guava Iterables Any Example | iDoDevJobs

  3. Pingback: Google Guava Optional Example | iDoDevJobs

  4. Pingback: Convert Map to String using Google Guava in Java | iDoDevJobs

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s