0

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?

  • Can you provide some example of what you want to achieve and what problems you are facing? – Pshemo Sep 13 '17 at 18:42
  • https://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html A Map that further provides a total ordering on its keys – Naman Sep 13 '17 at 18:47
  • TreeMap uses comparator for keys. It looks like you may be looking for [Sort a Map by values (Java)](https://stackoverflow.com/q/109383) – Pshemo Sep 13 '17 at 18:49
  • Also just curious, why can't you use `SortedMap carMap` instead? – Naman Sep 13 '17 at 18:59
  • The Integer is an id, Car isn't unique all times it can be repeating. – stuckhelper Sep 13 '17 at 19:06
  • can you use `guava`? cause if you do, you might look into `TreeMultimap`, where you can store multiple `Car`s that are the same according to `compareTo` – Eugene Sep 13 '17 at 19:25
  • And how can i compare only by value in TreeMultiMap? Can u write an example code? – stuckhelper Sep 14 '17 at 07:09
  • What decides that `car1` has id `1` and `car2` has id `2`? Why is the id not a property of the car? – Holger Sep 14 '17 at 10:35

0 Answers0