【问题标题】:Sort TreeMap Values In Alphabetical order按字母顺序对 TreeMap 值进行排序
【发布时间】:2018-10-30 19:40:23
【问题描述】:

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

TreeMap<String, Product>

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

其中 Product 是具有以下字段的自定义对象:

private String category;
private String name;

有没有办法用自定义对象做到这一点?我需要覆盖 compareTo 方法吗?

【问题讨论】:

标签: java sorting foreach treemap


【解决方案1】:

你应该给比较器

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

【讨论】:

    【解决方案2】:

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

    这是一个例子。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多