如何在数据类型不是字符串的情况下对ArrayList进行排序 Java?

huangapple go评论52阅读模式
英文:

How to sort an arrayList when the datatype is not a string Java?

问题

我有一个存储对象的ArrayList。每个对象包含字符串和整数。如何根据对象的字符串对这个ArrayList进行字母排序?(我尝试过使用Collections.sort(arrayList的名称),但由于ArrayList的数据类型不是字符串,它不会进行排序。)

英文:

I have an arrayList that stores objects. Each object contains string and integer. How can I sort this arrayList alphabetically based on the object's string? (I tried Collections.sort(arrayList's name) but since the arrayList's data type isn't a string, it won't sort.)

答案1

得分: 1

你需要传递一个自定义的比较器:

Collections.sort(list, (o1, o2) -> o1.getString().compareTo(o2.getString()));

或者实现Comparable接口:

public class YourClass implements Comparable<YourClass> {
   ...
   @Override
   public int compareTo(YourClass other) {
      //TODO: 错误处理
      return this.getString().compareTo(other.getString());
   }
}
//然后:
//Collections.sort(list);
英文:

You have to pass a custom Comparator:

Collections.sort(list,(o1,o2)-&gt;o1.getString().compareTo(o2.getString());

or implement the Comparable interface:

public class YourClass implements Comparable&lt;YourClass&gt;{
   ...
   @Override
   public int compareTo(YourClass other){
      //TODO: Error handling
      return this.getString().compareTo(other.getString();
   }
}
//and then:
//Collections.sort(list);

huangapple
  • 本文由 发表于 2020年8月9日 03:20:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/63319398.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定