简体   繁体   English

Java排序动态定义的对象数组列表

[英]Java sorting dynamically defined arraylist of objects

I want to sort this 我想排序

LG Electronics  1.jpg   
Apple   2.JPG   
Apple   3.JPG

As

Apple   2.JPG   
Apple   3.JPG
LG Electronics  1.jpg   

Here is my code //rows is 2d 这是我的代码//行是2d

ArrayList<String[]> rows = new ArrayList<>();
for(int i=0;i<images.length;i++){
    com.drew.metadata.Metadata metadata = ImageMetadataReader.readMetadata(images[i]);
    for (com.drew.metadata.Directory directory : metadata.getDirectories()) {
        for (Tag tag : directory.getTags()) {
            //System.out.println(tag.toString());
            if(tag.toString().contains("[Exif IFD0] Make")){
                rows.add(new String[]{tag.getDescription(),images[i].toString()});
            }
        }
    }
}

I have implemented Collections.sort(rows); 我已经实现了Collections.sort(rows); but nothing works for me. 但对我没有任何作用。 I even tried 我什至试过

Collections.sort(rows, new Comparator<ArrayList<String>>() {
    @Override
    public int compare(ArrayList<String> o1, ArrayList<String> o2) {
    return o1.get(0).compareTo(o2.get(0));
    }
    });

But it also doesn't works for me. 但这对我也不起作用。 I got this error that no suitable method found for sort(arraylist 我收到此错误,找不到适合于sort(arraylist

I would advise against using a model such as ArrayList<String[]> rows in your case because it really doesn't tell much about what the list is holding -- and it makes implementing the comparison clunky. 我建议不要在您的情况下使用诸如ArrayList<String[]> rows类的模型,因为它实际上并不能说明列表所包含的内容,并且会使比较笨拙。

Instead, you could model the metadata as a Java class: 相反,您可以将元数据建模为Java类:

public class Metadata {

  private final String description;
  private final String imageName;

  public Metadata(String description, String imageName) {
    this.description = description;
    this.imageName = imageName;
  }
  public String getDescription() {return description;}
  public String getImageName() {return imageName;}

  @Override
  public String toString() {
    return description + " " + imageName;
  }
}

Now, you can have a List<Metadata> rows = new ArrayList<>(); 现在,您可以拥有一个List<Metadata> rows = new ArrayList<>(); which you populate inside the loop only changing this part: 您在循环内填充的内容仅更改了此部分:

rows.add(new String[]{tag.getDescription(),images[i].toString()});

into this 进入这个

rows.add(new Metadata(tag.getDescription(), images[i].toString());

And finally, you can sort with a proper Comparator using 最后,您可以使用适当的Comparator进行排序

Collections.sort(rows, Comparator
                        .comparing(Metadata::getDescription)
                        .thenComparing(Metadata::getImageName));

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

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