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.


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 GoogleGuavaExample {

    private String input;

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

    public static void main(String[] args) {

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

        Map newMap = Maps.uniqueIndex(yourList, new Function() {
            public String apply(GoogleGuavaExample googleGuavaExample) {
                return googleGuavaExample.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.

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

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