创建<string,list =“”> </string,>的映射时出现问题

时间:2012-08-29 02:36:01

标签: java

我在下面的查询返回的db中有一行。要选择的列包括rec,head,amount。我想按头列对行进行排序。我尝试了Map其中两个列的head和list列表。

我已经发布了下面发布的非工作代码。如何将另一个列表附加到重复键列表中。文档说它替换了相同键的值,而我需要将它附加到列表值。我会非常感谢任何帮助。

Query q= session.createQuery("select tally_receipt_prefix, tally_receipt_no, tally_head, tally_amount from Tally_table where tally_system_date='"+fmtd_date+"' and tally_dbcr_indicator='DB' and tally_mode='Ca' order by tally_head,tally_receipt_prefix,tally_receipt_no"); System.out.println("query "+q);

List heads=new ArrayList();

for(Iterator it=q.iterate(); it.hasNext(); )
{
    Object[] row= (Object[]) it.next();

    payincash1=new LinkedHashMap<String, List>();

    heads.add((String)row[2]);

    List tails = null;
    tails=new ArrayList();
    tails.add((String)row[0]);
    tails.add((String)row[1]);
    tails.add((String)row[3]);

    System.out.println("heads in dao from iter 1: "+heads);  
    System.out.println("tails in dao from iter1 on: "+tails);

    if(heads.contains((String)row[2]))  // for head in temp list
    {
        System.out.println("in first if");
        if(payincash1.containsKey((String)row[2]))     
        {
            System.out.println("map if repeat: "+payincash1);
            payincash1.put((String)row[2],tails);
        }

    } 
    else
    {

        System.out.println("map if not repeat: "+payincash1);
        payincash1.put((String)row[2], tails);

    }

}

2 个答案:

答案 0 :(得分:4)

听起来更像是你想要一份清单

Map<String, List<List>>

这样的东西

然后你会得到类似的东西......

Map<String, List<List>> payincash1 = new LinkedHashMap<String, List<List>>();

heads.add((String) row[2]);

List tails = null;
tails = new ArrayList();
tails.add((String) row[0]);
tails.add((String) row[1]);
tails.add((String) row[3]);

System.out.println("heads in dao from iter 1: " + heads);
System.out.println("tails in dao from iter1 on: " + tails);

List master = payincash1.get((String)row[2]);
if (master == null) {

    master = new List();
    payincash1.put((String)row[2], master);

}

master.add(tails);

现在,就个人而言,我将创建一个包含所有这些信息的“数据”对象。

public class MyData {
    private String rec, head, amount, ??; // Apparently you have another variable I don't know about
    public MyData(String rec, String head, String amount, String ??) {
        // Initalise...
    }
    // Setters and getters not inclueded
}

然后你可以做这样的事情......

Map<String, List<MyData>> payincash1 = new LinkedHashMap<String, List<MyData>>();

MyData data = new MyData(row[0], row[1], row[2], row[3]);

List master = payincash1.get((String)row[2]);
if (master == null) {

    master = new List<MyData>();
    payincash1.put((String)row[2], master);

}

master.add(data);

哪个更干净(恕我直言)

答案 1 :(得分:4)

根据我的理解,您需要guava库的Multimap。