我读到了使用Comparator对ArrayLists进行排序,但在所有人们使用的例子中compareTo,根据一些研究,这是一个字符串的方法.
我想通过它们的一个属性对自定义对象的ArrayList进行排序:Date对象(getStartDay()).通常我会比较它们item1.getStartDate().before(item2.getStartDate())所以我想知道我是否可以这样写:
public class CustomComparator {
public boolean compare(Object object1, Object object2) {
return object1.getStartDate().before(object2.getStartDate());
}
}
public class RandomName {
...
Collections.sort(Database.arrayList, new CustomComparator);
...
}
Run Code Online (Sandbox Code Playgroud) 我想根据数字字段对搜索结果进行排序。在以下示例代码中,我想根据“年龄”字段进行排序。我从使用以下答案开始:
[如何在 Lucene 6 中对 IntPont 或 LongPoint 字段进行排序
但它确实基于排序的 SCORE。年龄还没有提升。
和
我在搜索功能中将 SortField.Type.SCORE 更改为 SortField.Type.LONG。但我得到:
字段“年龄”的意外文档值类型 NONE(预期 = NUMERIC)
这是我的代码:
public class TestLongPointSort {
public static void main(String[] args) throws Exception {
String indexPath = "/tmp/testSort";
Analyzer standardAnalyzer = new StandardAnalyzer();
Directory indexDir = FSDirectory.open(Paths.get(indexPath));
IndexWriterConfig iwc = new IndexWriterConfig(standardAnalyzer);
iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
IndexWriter masterIndex = new IndexWriter(indexDir, iwc);
Document doc = new Document();
String name = "bob";
doc.add(new TextField("name", name, Field.Store.YES));
doc.add(new SortedDocValuesField("name", new BytesRef(name)));
doc.add(new SortedNumericDocValuesField("age", …Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个程序,可以按字母顺序对ArrayList的内容进行排序.现在我的课程中有三节课......
狗
public class Dog {
private String name;
public Dog(){
}
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
}
Run Code Online (Sandbox Code Playgroud)
DogList(包含Dog类型的ArrayList)
import java.util.ArrayList;
public class DogList {
private ArrayList<Dog> dogList;
public DogList(){
DogList = new ArrayList<>();
}
public void setSize(int DogSize){
for(int x = 0; x <= DogSize; x++){
DogList.add(new Dog());
}
}
public ArrayList<Dog> getList(){
return dogList;
}
}
Run Code Online (Sandbox Code Playgroud)
最后一个类DogSorter,它试图访问DogList ArrayList,然后尝试按字母顺序对该ArrayList的内容进行排序.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class DogSorter …Run Code Online (Sandbox Code Playgroud)