simon
simon

Reputation: 12902

Shortest way to extract Map from List in Java

I have a List

List<FeatureHolder> featureHolderList;

consisting of FeatureHolder objects

public class FeatureHolder {
   private String  flag;
   private String  value;
}

Now I need to extract Map from the featureSetList. The solution is, of course, trivial:

    Map<String, String> map = new HashMap<>();
    for(FeatureHolder fh: featureHolderList){
        map.put(fh.getFlag(), fh.getValue());
    }

The question is, is there a better (shorter) way of doing this in Java 7? I have looked into e.g. Google Collections and the method Maps.uniqueIndex, but the code required to perform the transformation this way would be much longer, and arguably less readable.

Upvotes: 1

Views: 4888

Answers (4)

Fritz Duchardt
Fritz Duchardt

Reputation: 11860

Often I find the decision whether to use Guava or not difficult. According to the Guava's own caveats docu, you should refrain from using Guava, if there is no net saving of lines of code or a clear performance benefit.

However, in your case I fail to see an easy way to create your Map with Guava at the first place, since Maps.uniqueIndex only comes with a key mapping function, but no value mapping function. This means, you would end up with a map of type Map<String, FeatureHolder>.

If you can use Java 8, Collectors.toMap could be an option, but in my option nothing can't beat your "plain old 3 lines of easy to read code" solution, so please stick to it!

Upvotes: 2

Arjit
Arjit

Reputation: 3456

Use Google collections

Map<String, String> map = Maps.uniqueIndex(yourList, Functions.toStringFunction());

Upvotes: 0

user3644708
user3644708

Reputation: 2495

with Java 7, your code is fine.

or you can use Java 8

Map<String, Item> map = list.stream()
                        .collect(Collectors.toMap(Item::getKey,
                                                  item -> item));

Upvotes: 5

Tagir Valeev
Tagir Valeev

Reputation: 100139

You code is just fine, it's unlikely that you can do it shorter in Java 7. Just to make it a little more optimal you may add a default capacity for HashMap if you expect that all flags are different:

Map<String, String> map = new HashMap<>(fhList.size());

It's a little bit longer, but may work faster as rehashing will not be necessary.

Upvotes: 0

Related Questions