0

我们如何对两个大小不等的列表以及 pojo 类字段没有实现 equals/hashcode 方法的位置进行排序。我无法根据 list1 顺序对列表进行排序。我希望列表中发生的顺序有“t”然后“ s"。是否有可能实现这种情况?

Field f=new Field();
f.setKey("s");
f.setValue("he");

Field f1=new Field();
f1.setKey("t");
f1.setValue("she");

List<Field> list = new ArrayList<Field>();
list.add(f);
list.add(f1);

Field f2=new Field();
f2.setKey("t");
f2.setValue("he");

Field f3=new Field();
f3.setKey("s");
f3.setValue("she");

Field f4=new Field();
f4.setKey("u");
f4.setValue("she");

List<Field> list1 = new ArrayList<Field>();
list1.add(f2);
list1.add(f3);
list1.add(f4);
4

3 回答 3

1

您可以使用Collections.sort(list, new Comparator<Field>() { /* ... */ });

Javadoc

于 2012-09-12T08:44:34.697 回答
0

没有内置方法可以实现您想要的,但是您可以Collections.sort通过提供自己的比较器轻松地做到这一点:

Collections.sort(list, new Comparator<Field>() {
    @Override
    public int compare(Field f1, Field f2) {
        // compare your fields here and
        //     return -1 if f2 should be before f2
        //     return 0 if they are the same
        //     return 1 if f1 should be after f2

        return ...;
    }
});
于 2012-09-12T08:47:06.877 回答
0

试试这样的东西:

import java.util.HashMap; 
import java.util.Map.Entry; 
public class HashMapComparison 
{     
 public static void main(String[] args) 
 {        
 HashMap<Integer, String> map1 = new HashMap<Integer, String>();   
 map1.put("s", "he");     
 map1.put("t", "she");    
 HashMap<Integer, String> map2 = new HashMap<Integer, String>();  
 map2.put("t", "he");     
 map2.put("s", "she");  
 map2.put("u", "she"); 
 HashMap<Integer, String> orderedMap1 = new HashMap<Integer, String>();  
 for (Entry<Integer, String> entry : map2.entrySet()) {      
 Integer key = entry.getKey();        
 for(Entry<Integer, String> entry : map1.entrySet()){
 if(key.equals(entry.getKey()){
   orderedMap1.put(entry);
 }
 }
 }     
 } 
于 2012-09-12T09:04:25.657 回答