0

I'm trying to sort a TreeMap by its values so I can print out the values in alphabetical order based on the name of that particular object.

TreeMap<String, Product>

for(Product item : map.values()){
  System.out.println(item.getName());
}

Where Product is a custom object with the following fields:

private String category;
private String name;

Is there a way to do this with custom objects? Will I need to overwrite the compareTo method?

  • But you did not sort by values! You just printed values as is (in fact, sorted by String key) – Oleksii Morenets Oct 30 '18 at 19:44
  • Yes, that's my question is it possible to sort the values :) – Frederik Jorgensen Oct 30 '18 at 19:47
  • See this [related question](https://stackoverflow.com/questions/53071749/sort-treemap-values-in-alphabetical-order). – Andrew S Oct 30 '18 at 19:50
  • These two resources could be helpful: [Treemap sort by value](https://stackoverflow.com/questions/2864840/treemap-sort-by-value), [Sort objects by property](https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) – vinayawsm Oct 30 '18 at 19:50
  • Possible duplicate of [TreeMap sort by value](https://stackoverflow.com/questions/2864840/treemap-sort-by-value) – Marvin Oct 30 '18 at 19:51

2 Answers2

0

You should give the Comparator

map.values().stream()
            .sorted(Comparator.comparing(Product::getName))
            .forEach(System.out::println);

OR if you don't want to loose keys:

map.entrySet().stream()
            .sorted(Comparator.comparing(o -> o.getValue().getName()))
            .forEach(System.out::println);
0

I was going through the same thing and I thought this could be helpful for someone looking for/will need to sort the treemap value by its instances (I wanted to sort the items by names in the list of the treemap value). I know this is a pretty old post but, hopefully it might be helpful for someone...

Here is an example.

//Implementing the Comparator interface to compare the 
//Animal object by its name instance

class Animal implements Comparator<Animal> { 

...

@Override
public int compare(Animal o1, Animal o2) {
    return o1.getName().compareTo(o2.getName());
    }
}

//instantiated a new treemap with a list value 
TreeMap<String, List<Animal>> treeMap = new TreeMap<String, List<Animal>>( );

//While looping through the animals to add animal object from the list to treemap by its
//owner as a key, I called treemap key and sorted with perspective animal
for(Animal animal: animals){

        key = animals.get(count).getOwner();

        if(treeMap.containsKey(key)){
            treeMap.get(key).add(animal);
        }else {
            List<Animal> animalList = new ArrayList<Animal>();
            animalList.add(animal);
            treeMap.put(animal.getOwner(), animalList);
        }

        //I am sorting the animal object
        treeMap.get(key).sort(animal); 
    }

Please, feel free to edit if you have better options, I'd love to discover ;)