我有一个如下的哈希图:

someMap= new HashMap<Integer, String>();
someMap.put(1, "variable1");
someMap.put(2, "variable2");
someMap.put(3, "variable3");
someMap.put(4, "variable4");
someMap.put(5, "variable5");


而且我有一个像下面这样的java类:

public class SomeVO {

      Long someNumber;
      String  shortDesc;

    public Long getSomeNumber() {
        return someNumber;
    }
    public void setSomeNumber(Long someNumber) {
        this.someNumber = someNumber;
    }

    public String getShortDesc() {
        return shortDesc;
    }
    public void setShortDesc(String shortDesc) {
        this.shortDesc = shortDesc;
    }

}


在数据库中,我有像

someNumber and short-description


当我查询数据库时,我返回一个包含以上信息的列表:

List<SomeVO > existingSomeNumberAndShortDescriptionList


现在,我必须将此ListsomeMap进行比较,并返回两个映射,这些映射将具有变量作为键和该变量的简短说明。

像我必须与existingSomeNumberAndShortDescriptionList进行比较,我需要像

variable1,shortDescription(此数据来自数据库,可在existingSomeNumberAndShortDescriptionList中使用),

以及variable1,Y或N(如果在List中可以使用someNumber而不是Y否则N

最佳答案

您的代码将如下所示:

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {


    // Loaded Hashmap-------------------------------------------------------------------

    HashMap<Long, String> someMap= new HashMap<Long, String>();
    someMap.put(1L, "variable1");
    someMap.put(2L, "variable2");
    someMap.put(3L, "variable3");
    someMap.put(4L, "variable4");
    someMap.put(5L, "variable5");


    // List getting from db-------------------------------------------------------------------

    List<SomeVO> existingSomeNumberAndShortDescriptionList  = new ArrayList<SomeVO>();

    SomeVO someVO1=new SomeVO();
    someVO1.setSomeNumber(1L);
    someVO1.setShortDesc("Description 1");

    SomeVO someVO2=new SomeVO();
    someVO2.setSomeNumber(2L);
    someVO2.setShortDesc("Description 2");

    existingSomeNumberAndShortDescriptionList.add(someVO1);
    existingSomeNumberAndShortDescriptionList.add(someVO2);

    //--------------------------------------------------------------------------------------------


    HashMap<String, String> hashmap1 =new HashMap<String, String>();
    HashMap<Long, String> hashmap2 =new HashMap<Long, String>();

    //Iterate through list of bean
    for (Iterator<SomeVO> iterator = existingSomeNumberAndShortDescriptionList .iterator(); iterator.hasNext();) {
        SomeVO someVO = (SomeVO) iterator.next();

        // Compare key with main hashmap and Put in hashmap 1
        hashmap1.put(someMap.get(someVO.getSomeNumber()),someVO.getShortDesc());

        // Compare key with main hashmap and check if number exists and Put in hashmap 2
        if(someMap.containsKey(someVO.getSomeNumber()))
            hashmap2.put(someVO.getSomeNumber(),"Y");
        else
            hashmap2.put(someVO.getSomeNumber(),"N");
    }


    // print hashmaps
    System.out.println(hashmap1);
    System.out.println(hashmap2);

}


和输出将..

{variable1=Description 1, variable2=Description 2}
{1=Y, 2=Y}

09-30 18:42
查看更多