有时候我们需要将给定的 List 转换为 Map。

如果你使用的是 Java 8 以后版本的话,Stream 是你的好朋友。

java中list转json java中list转map对象_Java

Java 8

public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
    Map<Integer, Animal> map = list.stream()
      .collect(Collectors.toMap(Animal::getId, Function.identity()));
    return map;
}

上面的代码可以非常容易的完成转换,我们有一个 Animal 对象的 List。

上面的代码将会把 Id 作为 Key,然后生成的 Map 是以 id 为 Key,Animal 为Value 的 Map。

Guava

如果使用 Guava 就更加简单了。

public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
    Map<Integer, Animal> map = Maps
      .uniqueIndex(list, Animal::getId);
    return map;
}

使用 Maps 的工具类就可以了,这个工具类可以直接用。

更进一步

如果对需要生成的 Map 进行处理。

Key 是对象中的一个值,Value 是 List 对象中的另外一个值。

例如可以使用下面的代码:

listingStatusList.stream().collect(Collectors.toMap(CListingStatus::getListingStatusKey, CListingStatus::getListingStatus));

其中 CListingStatus 对象是这样定义的。

@Entity
@Getter
@Setter
public class CListingStatus extends AbstractPersistable<Long> {

    @ManyToOne
    @JoinColumn(name = "rets_id", nullable = false)
    private ConfRets confRets;

    private String listingStatusKey;

    private ListingStatus listingStatus ;

}

对 Map 中的对象设值

针对 Stream 中的对象,我们可能还需要重新设置为其他的对象。

这个时候我们就可以使用 lambda 函数了。

同样的代码:

HashMap<String, Agent> agentHashMap = (HashMap) mlsAgentList.stream().collect(Collectors.toMap(MlsAgent::getMlsAgentId, mlsAgent -> {
            Agent agent = new Agent();
            agent.setAgentId(mlsAgent.getMlsAgentId());
            agent.setAgentNameFirst(mlsAgent.getNameFirst());
            agent.setAgentNameLast(mlsAgent.getNameLast());
            agent.setAgentEmail(mlsAgent.getEmail());
            return agent;
        }));

我们返回的 Map 使用了一个新的对象为 Value。

上面针对 Stream 转换为 Map 的方法进行了一些小总结,这些方法可能实际编程的时候使用的频率比较高。

同时能够避免大量使用 For 循环的情况。

Stream 还是需要好好了解下的。