简体   繁体   中英

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 eg 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.

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));

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!

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.

使用Google收藏夹

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM