将对象列表转换为映射

时间:2016-06-12 06:24:13

标签: java

我有两个属性{alpha,beta}的对象列表如下:

btn1.setOnClickListener(new OnClickListener(){
     @Override
     public void onClick(View view) {
          if(btn1.getText().toString().equals("Correct Answer")){
             questionPos++;
             imgView.setImageResource(questionPos);
             // Update all the buttons as per the new options
             btn1.setText(options1);
          }
     }
});

// Similarly you can do for all other buttons

我想创建一个地图,例如obj1 = {alpha1,beta1} obj2 = {alpha2,beta2} obj3 = {alpha3,beta3} obj3 = {alpha1,beta2} obj5 = {alpha3,beta1}

所以它将在下面:

Map<alphaKey,List<beta>>

由于

3 个答案:

答案 0 :(得分:0)

请在 google guava lib

中尝试 Multimap

答案 1 :(得分:0)

Map<alphaKey, List<beta>> map = new HashMap<alphaKey, List<beta>>();

    for (int i = 0; i < objList.size(); i++) {
        boolean isContain = map.containsKey(objList.get(i).getAlphaKey());
        if (isContain)
            map.get(objList.get(i).getAlphaKey())
                    .add(objList.get(i).getBeta());
        else {
            List<beta> betaList = new ArrayList<beta>();
            betaList.add(objList.get(i).getBeta());
            map.put(objList.get(i).getAlphaKey(), betaList);
        }

    }

答案 2 :(得分:0)

public class ObjectAB {
    Alpha a;
    Beta b;
    // Gettters and constructuor
}

    ObjectAB[] objArray = new ObjectAB[5]; 
// add obj1, obj2 to it.


    Map<Alpha, List<Beta>> map1 = new HashMap<>();
    for (ObjectAB objectAB : objArray) {
        Alpha a = objectAB.getA();
        List<Beta> bList = new ArrayList<>();
        if (map1.containsKey(a)) {
            bList = map1.get(a);
        }
        bList.add(objectAB.getB());
        map1.put(a, bList);
    }