简体   繁体   English

按字母顺序对 TreeMap 值进行排序

[英]Sort TreeMap Values In Alphabetical order

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 进行排序,以便我可以根据该特定对象的名称按字母顺序打印出这些值。

TreeMap<String, Product>

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

Where Product is a custom object with the following fields:其中 Product 是具有以下字段的自定义对象:

private String category;
private String name;

Is there a way to do this with custom objects?有没有办法用自定义对象来做到这一点? Will I need to overwrite the compareTo method?我需要覆盖 compareTo 方法吗?

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);

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 ;)如果您有更好的选择,请随时进行编辑,我很想发现 ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM