Losing sort order converting a List to a Map using Java Streams

48 views Asked by At

I have a bit of code that receives a list of objects of a class called Metric. The list comes in sorted by name. I am then using the Java Streams API to convert the list to a map, with the name as the key and the value as the Metric object.

Metric.java:

public class Metric implements Comparable<Metric> {

  private String              name;
  private String              type;
  // ... other fields

  // Getters/Setters removed

  @Override
  public int compareTo(Metric o) {
    if (this.name.equals(o.name)) {
      return this.type.compareTo(o.type);
    }

    return this.name.compareTo(o.name);
  }

}

I'm using the following code to perform the list to map conversion:

map = allMetrics.stream().collect(Collectors.toMap(Metric::getName, Function.identity()));

I've discovered that the resulting map is no longer ordered by name. I tried adding sorted() in front of the collect() call, but that had no effect.

I then dug into the Collectors class to see if I could figure out what's going on. It turns out the Collectors.toMap() methods use a new HashMap internally to store the map. I think that's what's messing up the order.

Does anyone know of an alternate way to achieve the list to map conversion and not lose the ordering?

0

There are 0 answers