Java:如何将带有arraylist的Comparator用作HashMap的值

时间:2015-08-28 21:44:31

标签: java

我有这个HashMap:

 HashMap< itemDetails, Pair<ArrayList<itemDetails>, AssociatedInfo>> AssociatedItemCasuaList = new HashMap<>();

其键是class,其值由pair(a =类 itemDetails 的arraylist,b = class AssociatedInfo )组成:

class itemDetails {
    public ArrayList<Integer> itemId; 
    public float expectedSupport = 0;
    // etc
}

  class Pair<T, U> {

        T a;
        U b;

        Pair(T a, U b) {
            this.a = a;
            this.b = b;
        }

        T getA() {
            return a;
        }

        U getB() {
            return b;
        }
    }

class AssociatedInfo { 
    public int noOfKCasual = 0;
    public int AssociateListStart = 0;
    public int AssociateListEnd = 0;
}

我想对HashMap的第一对值进行排序 这是班级ArrayList<Integer> itemId

中的itemDetails

我用过这个比较器

 public class ItemComparator implements Comparator<ArrayList<Integer> >{
     @Override
    public int compare(final ArrayList<Integer> entry1, final ArrayList<Integer> entry2){
        if (entry1 == null && entry2 == null)
            return 0;
        if (entry1 == null)
            return 1;
        if (entry2 == null)
            return -1;
        if (entry1.isEmpty() && entry2.isEmpty())
            return 0;
        if (entry1.isEmpty())
            return 1;
        if (entry2.isEmpty())
            return -1;
        return entry1.get(0).compareTo(entry2.get(0));
    }
  }

我不知道如何撰写Collections.sort

if (AssociatedItemCasuaList.containsKey(LHS)) {
    AssociatedItemCasuaList.get(LHS).a.add(RHS2);
    AssociatedItemCasuaList.get(LHS).b.AssociateListStart = 0;
    AssociatedItemCasuaList.get(LHS).b.AssociateListEnd += 1;
    AssociatedItemCasuaList.get(LHS).b.noOfKCasual += 1;
} else {
    ArrayList<itemDetails> ArrayListRHS = new ArrayList<itemDetails>();
    ArrayListRHS.add(RHS2);
    AssociatedInfo AttribAssociatedInfo1 = new AssociatedInfo();
    AttribAssociatedInfo1.noOfKCasual = 1;
    AttribAssociatedInfo1.AssociateListStart = 0;
    AttribAssociatedInfo1.AssociateListEnd = 0;
    AssociatedItemCasuaList.put(LHS, new Pair(ArrayListRHS, AttribAssociatedInfo1));
}
//      Collections.sort(AssociatedItemCasuaList.get(LHS), new ItemComparator());

更新: 例如:

AssociatedItemCasuaList < **key**=LHS, **value**=Pair<a, b> >

设键= LHS:

LHS.itemId=1
LHS.expectedSupport=87.5

和值=对&lt; a,b&gt;

让我们只关注此示例中的a

a= ArrayList<itemDetails> 

itemDetails RH2

每次(循环中)我将 RHS2 添加到关键 LHS 中:

AssociatedItemCasuaList.get(LHS).a.add(RHS2)

此处RHS2每次都会使用不同的值

  RHS2.itemId
  RHS2.expectedSupport
直到现在,我没有问题。

我想基于itemId对a(我填充RHS2)中的ArrayList进行排序

1 个答案:

答案 0 :(得分:0)

忽略我不理解一个词的事实,这是怎么回事:

public class ItemComparator2 implements Comparator<itemDetails> {
  Comparator myComp = new ItemComparator();
  @Override
  public int compare(itemDetails a, itemDetails b){
    return myComp.compare(a.itemId, b.itemId);
  }
}

// ...

Collections.sort(AssociatedItemCasuaList.get(LHS).getA(), new ItemComparator2());