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

时间:2018-10-30 19:40:23

标签: java sorting foreach treemap

我正在尝试按TreeMap的值对它们进行排序,以便可以根据该特定对象的名称按字母顺序打印出这些值。

TreeMap<String, Product>

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

产品是具有以下字段的自定义对象:

private String category;
private String name;

是否可以使用自定义对象来执行此操作?我需要覆盖compareTo方法吗?

2 个答案:

答案 0 :(得分:0)

您应该给比较器

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

或 如果您不想放开钥匙:

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

答案 1 :(得分:0)

我正在经历同样的事情,我认为这可能对寻找/需要按实例对树图值进行排序的人有所帮助(我想按树图值列表中的名称对项目进行排序)。我知道这是一个很旧的帖子,但希望它可能对某人有所帮助...

这是一个例子。

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

如果您有更好的选择,请随时进行编辑,我很乐意发现;)

相关问题