user3892260
user3892260

Reputation: 1035

Transform a list of maps to a map that uses ImmutablePair with Java 8 streams

How can I rewrite this old style of code to use Java 8 streams? I know it can be done with a single line of stream code.

Map<String, ImmutablePair<Double, Double>> dataCache = new LinkedHashMap<>()
List<Map<String, Object>> data = new ArrayList<>();
for(Map<String, Object> rec : data) {
    String code = (String) rec.get("code");
    Double x0 = (Double) rec.get("x0");
    Double x1 = (Double) rec.get("x1");
    dataCache.put(code, new ImmutablePair<>(x0, x1));
}

Essentially the idea is to remap a generic list of records into a more structured hash lookup.

Upvotes: 1

Views: 778

Answers (2)

Louis Wasserman
Louis Wasserman

Reputation: 198211

Map<String, ImmutablePair<Double, Double>> dataCache = data.stream()
   .collect(
       Collectors.toMap(
          rec -> (String) rec.get("code"),
          rec -> new ImmutablePair<>(
              (Double) rec.get("x0"), (Double) rec.get("x1"))));

If you care about the map implementation, you probably want

Map<String, ImmutablePair<Double, Double>> dataCache = data.stream()
   .collect(
       Collectors.toMap(
          rec -> (String) rec.get("code"),
          rec -> new ImmutablePair<>(
              (Double) rec.get("x0"), (Double) rec.get("x1")),
          (p1, p2) -> { throw new IllegalArgumentException(); },
          LinkedHashMap::new));

Upvotes: 3

Andreas
Andreas

Reputation: 159135

Since you want a single line of stream code:

Map<String, ImmutablePair<Double, Double>> dataCache = data.stream().collect(Collectors.toMap(rec -> (String) rec.get("code"), rec -> new ImmutablePair<>((Double) rec.get("x0"), (Double) rec.get("x1")), (a, b) -> b, LinkedHashMap::new));

Upvotes: 3

Related Questions