-1

hello I'm new to the java world I have a question about how to convert a list to a map by use tree metrics.

public class AdditionalMetrics implements Serializable {
    private static final long serialVersionUID = 3813944465194104658L;

    private Long id;
    private String masterId;
    private String nodeKey;
    private String nodeValue;
}

I want to convert List<AdditionalMetrics> to Map<masterId, Map<nodeKey, nodeValue> and I search on the Internet it just shows

additionalMetrics.stream()
    .collect(Collectors.toMap(AdditionalMetrics::getMasterId,
                              AdditionalMetrics::getNodeValue)
ernest_k
  • 44,416
  • 5
  • 53
  • 99
yang xu
  • 55
  • 4

1 Answers1

1

You can't use toMap() because you have many nodeKey/nodeValue pairs to map to a single masterId value (unless you use a merge function).

This is easier to do grouping by masterId:

Map<String, Map<String, String>> result = additionalMetrics.stream()
        .collect(Collectors.groupingBy(
                AdditionalMetrics::getMasterId,
                Collectors.toMap(AdditionalMetrics::getNodeKey, 
                        AdditionalMetrics::getNodeValue)));
ernest_k
  • 44,416
  • 5
  • 53
  • 99