我想按任务列表排序,先按日期排序,然后按taskID排序 下面是代码
public static void main(String[] args) throws SQLException, UnknownHostException{
DB database = DB.getDatabase();
database.connect();
MD5Hasher h = new MD5Hasher();
UserDAOImpl d = new UserDAOImpl();
User s = new User();
s.setNickname("davide");
s.setPassword("ciao");
if(d.insert(s))
System.out.println("insert");
// d.delete(s);
for(User x : d.findAll()){
System.out.println("Nickname: "+x.getNickname()+" password: "+x.getPassword()+" matches: "+x.getTotalMatches());
}
}
我使用Collections.sort方法进行排序但是通过这个我可以按日期或ID排序。 如果按日期排序
ArrayList<fullist> taskdet = new ArrayList<fullist>();
public static class fullist
{
public int date;
public int id;
public fullist(int id, int date) {
this.date = date;
this.id = id;
}
}
这是显示的输出:
Collections.sort(taskdet, new Comparator<fullist>() {
@Override
public int compare(fullist o1, fullist o2) {
//if(o1)
return Integer.compare(o1.date, o2.date);
}
});
如果按ID排序。
day 19 ID 2
day 19 ID 1
day 19 ID 3
day 20 ID 2
day 20 ID 1
day 20 ID 3
这是显示的输出:
Collections.sort(taskdet, new Comparator<fullist>() {
@Override
public int compare(fullist o1, fullist o2) {
//if(o1)
return Integer.compare(o1.date, o2.date);
}
});
但输出应为:
day 20 ID 1
day 19 ID 1
day 19 ID 2
day 20 ID 2
day 20 ID 3
day 19 ID 3
答案 0 :(得分:2)
如果您使用Java 8,您可以写:
taskdet.sort(comparingInt(fullist::getDate).thenComparingInt(fullist::getId));
这假设您有getDate
和getId
个getter以及此静态导入:
import static java.util.Comparator.comparingInt;
答案 1 :(得分:2)
另一个不错的解决方案是使用Guava ComparisonChain:
public int compare(fullist o1, fullist o2) {
return ComparisonChain.start()
.compare(o1.date, o2.date)
.compare(o1.id, o2.id)
.result();
}
答案 2 :(得分:1)
如果Comparator
值相同,则需要id
来比较date
值。
@Override
public int compare(fullist o1, fullist o2) {
int comp = Integer.compare(o1.date, o2.date);
if (comp == 0)
{
comp = Integer.compare(o1.id, o2.id);
}
return comp;
}
答案 3 :(得分:0)
这将有效:
Collections.sort(taskdet, new Comparator<Fullist>() {
@Override
public int compare(fullist o1, fullist o2) {
int res = Integer.compare(o1.date, o2.date);
if(res == 0)
return o1.id - o2.id
return res;
}
});
答案 4 :(得分:0)
使用Java8:
.