Java 8 compare map by value bean's field

774 views Asked by At

How can i create a sorted map which compares by value's bean's field. Map key is Integer and value is the Car. I'd like to compare by car's name it's can contains no only letters.

Something like this: (it's not work, only a bad example)

Comparator<Car> carNameComparator = new Comparator<Car>() {
    @Override 
    public int compare(Car c1, Car c2) {
        return c1.getName().compareToIgnoreCase(c2.getName());
    }     
};
SortedMap<Integer,Car> carMap = new TreeMap<>(carNameComparator);

Second try:

Map<Integer, Car> carMap = new HashMap<>();
carMap.put(1, car1);
carMap.put(2, car2);

Map<Integer, Car> sortedByValue = carMap.entrySet().stream()
        .sorted(Map.Entry.<Integer, Car> comparingByValue(carNameComparator))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));


sortedByValue.forEach((k,c)->System.out.println("Key : " + k + " Value : " + c.getName()));

Maybe the second can be the right solution, somebody know a better solution, where don't need to create an other map?

0

There are 0 answers