Java HashMap和ArrayList顺序
我有Java HashMap和ArrayList顺序,java,Java,我有HashMap和ArrayList我正在用以下代码添加数据: conversationsMap.put(sendName,new Conversation(receiverName,currentTime)); conversationsList=new ArrayList<Conversation>(conversationsMap.values()); 我想通过currentTime订购conversationsList,他们没有使用此代码订购。conversationsL
HashMap
和ArrayList
我正在用以下代码添加数据:
conversationsMap.put(sendName,new Conversation(receiverName,currentTime));
conversationsList=new ArrayList<Conversation>(conversationsMap.values());
我想通过currentTime
订购conversationsList
,他们没有使用此代码订购。conversationsList
应如下所示:
conversation.getTime();
1)当前时间:10
2)当前时间:9
2)当前时间:8
...
我怎样才能做到这一点?我想我需要使用一个循环来获取值,然后添加到conversationsList
私有类CustomComparator实现Comparator{
private class CustomComparator<T extends Conversation> implements Comparator<Conversation>{
public int compare(Conversation loBean1, Conversation loBean2) {
if(obj1.getTime()<obj2.getTime()) {
return -1;
} else if(obj1.getTime()>obj2.getTime()) {
return 1;
} else {
return 0
}
}
}
Collections.sort(conversationsList, new CustomComparator<Conversation>());
公共整数比较(会话loBean1、会话loBean2){
if(obj1.getTime()obj2.getTime()){
返回1;
}否则{
返回0
}
}
}
排序(conversationsList,new CustomComparator());
您还可以实现类似的接口。。然后像这样做
public class Conversation implements Comparable<Conversation>
公共类会话实现了可比较的
{
int当前时间;
public int getCurrentTime()
{
返回时间;
}
公共无效setCurrentTime(int currentTime)
{
this.currentTime=currentTime;
}
@凌驾
公共int比较(对话o)
{
int-ret=0;
如果(this.currentTime>o.getCurrentTime())
{
ret=1;
}
else if(this.currentTime
}如果您需要在一个地方使用它,那么您可以动态创建比较器
conversationsMap.put(sendName,新会话(receiverName,currentTime));
conversationsList=新的ArrayList(conversationsMap.values());
Collections.sort(conversationsList,newcomparator()
{
@凌驾
公共整数比较(会话obj1、会话obj2)
{
if(obj1.getTime()obj2.getTime()){
返回1;
}否则{
返回0
}
}
});代码>您必须为此编写一个自定义比较器,并在列表中使用它。您可以给出一个示例吗?无法在原语类型上调用compareTo(long)long如何解决此问题?谢谢,它正在工作,但它是按ASC排序的,我需要按desc排序。我想您正在寻找一种方法来完成所需的操作,而不是确切的答案:)
int currentTime;
public int getCurrentTime()
{
return currentTime;
}
public void setCurrentTime(int currentTime)
{
this.currentTime = currentTime;
}
@Override
public int compareTo(Conversation o)
{
int ret = 0;
if (this.currentTime > o.getCurrentTime())
{
ret = 1;
}
else if (this.currentTime < o.getCurrentTime())
{
ret = -1;
}
return ret;
}