QSY
QSY

Reputation: 127

How to sort a Map by value in multi layer

Here is the map with the following structure:

Map<String, Oddcurve> curves;

class Oddcurve entends Curve {
    private String curvename;
}

class Curve {
    private int curveId;
    protected Set<CurvePoint> points = new TreeSet();
}

class CurvePoint {
    private double time;
    private double value;
}

I want to sort the curves by the time ASC, and finally return still the same map :

proxyCurves.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue));

I write in this way, When i debug it, I can see that the sorting works fine, but finally still returns the original curves, I don't know why?

proxyCurves.values().stream().forEach(curve -> curve.setPoints(curve.getPoints().stream().sorted(new ComparableComparator<>()).collect(Collectors.toSet())));

Upvotes: 0

Views: 71

Answers (2)

QSY
QSY

Reputation: 127

This is the code I use to solve the problem:

curves.values().stream().forEach(
            curve -> {
                final Set<CurvePoint> sortedPoints = new TreeSet<>(
                        (curvePoint1, curvePoint2) -> Double.compare(curvePoint1.getTime(), curvePoint2.getTime()));
                sortedPoints.addAll(curve.getPoints());
                curve.setPoints(sortedPoints);
            });

Upvotes: 0

Shahnur Isgandarli
Shahnur Isgandarli

Reputation: 161

  • Firstly, I would advise you to override hashCode() and equals() methods (you may run into issues because of that).
  • Secondly, I would advise you to implement Comparable interface in CurvePoint class because you are using TreeSet. Then you will be able to override compareTo() method, and define your way of sorting.

Upvotes: 1

Related Questions