-4

如何打印??

LINE1 "A"=1, "B"=1, "C"=3
LINE2 "A"=1, "B"=1, "C"=2
LINE3 "A"=1, "B"=11, " C"=2
LINE4 "A"=1, "B"=2, "C"=2
LINE5 "A"=1, "B"=1, "C"=11

    ArrayList mylist = new ArrayList();

    Map<String,Integer> mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",3);
    mylist.add(mMap); 

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",2);
    mylist.add(mMap); 

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",11);
    mMap.put("C",2);
    mylist.add(mMap);

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",2);
    mMap.put("C",2);
    mylist.add(mMap);

    mMap = new HashMap<String,Integer>();
    mMap.put("A",1);
    mMap.put("B",1);
    mMap.put("C",11);       
    mylist.add(mMap);
4

3 回答 3

1

尝试这个 -

for (Map<String, Integer> map : mylist) {
    for (Entry<String, Integer> entry : map.entrySet()) {
        System.out.print("\""+entry.getKey()+"\"="+entry.getValue()+" ");
    }
    System.out.println("\n");
}

输出 -

“A”=1 “B”=1 “C”=2

“A”=1 “B”=1 “C”=3

“A”=1 “B”=1 “C”=11

“A”=1 “B”=2 “C”=2

“A”=1 “B”=11 “C”=2

于 2013-02-04T07:58:48.843 回答
1
int counter = 1;
StringBuffer buffer = new StringBuffer();

for (Map<String,Integer> map : mylist) {
    buffer.append("LINE");
    buffer.append(counter++);

    for (Entry<String, Integer> entry : map.entrySet()) {
        String key = entry.getKey();
        Object value = entry.getValue();

        buffer.append(" \"");
        buffer.append(key);
        buffer.append("\"=");
        buffer.append(value);
        buffer.append(", ");
    }

    String s = buffer.toString().trim().substring(0, buffer.length() - 2);
    System.out.println(s);
    buffer.delete(0, buffer.length());
}

只需将其放在代码的末尾即可..

顺便说一句,将您的第一行更改为

ArrayList<Map<String,Integer>> mylist = new ArrayList<Map<String, Integer>>();

这将导致

LINE1 "A"=1, "B"=1, "C"=3
LINE2 "A"=1, "B"=1, "C"=2
LINE3 "A"=1, "B"=11, "C"=2
LINE4 "A"=1, "B"=2, "C"=2
LINE5 "A"=1, "B"=1, "C"=11

编辑:在行号后添加空格

于 2013-02-04T08:07:43.607 回答
0

略有不同的解决方案:

   final String A = "A";
   final String B = "B";
   final String C = "C"; 
   for (int i = 0; i < mylist.size(); i++) {
       Map<String, Integer> map = mylist.get(i);
       System.out.println(String.format("LINE%d \"A\"=%d,\"B\"=%d,\"C\"=%d", i, map.get(A), map.get(B), map.get(C)));
   }
于 2013-02-04T08:03:38.317 回答