For-Each Loop,Map <string,map <string,=“”list <string =“”>&gt;&gt;

时间:2016-07-27 15:36:24

标签: java swing

如何更改代码中的For-Each循环部分。它应该像这样工作

当我在窗口中写“Mark”并点击okay(下一个Alina等)时,应显示下方:

[A]

    [l]
        - Alina
    [d]
        - Adam
[M]

    [a]

         - Mark

enter image description here

public class WordsList extends ArrayList {

@Override
public String toString() {
    if (isEmpty()) {
        return "[]";
    }
    return String.format("[%s]\n", stream().collect(Collectors.joining(",")));     
   }
}

测试类

private Map<String, Map<String, List<String>>> words = new HashMap<>();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    String key = ("" + jTextField1.getText().charAt(0)).toUpperCase();
    Map<String, List<String>> firstLevel = words.get(key);
    String value = jTextField1.getText();

    if (firstLevel == null) {
        firstLevel = new HashMap<>();
        words.put(key, firstLevel);
    }

    List<String> secondLevel = firstLevel.get("" + jTextField1.getText().charAt(1));

    if (secondLevel == null) {
        secondLevel = new ArrayList<>();
        firstLevel.put("" + jTextField1.getText().charAt(1), secondLevel);
    }

    secondLevel.add(value);

    jTextArea1.setText("");

    for (String keys : words.keySet()) {
        jTextArea1.append("[" + keys + "]\n");            
        for (String keyss : firstLevel.keySet()) {
            jTextArea1.append("        " + "[" + keyss + "]\n");                
            for (String keysss : secondLevel) {
                jTextArea1.append("           " + "-" + keysss + "\n");
            }
        }
    }
}                                  

我也是Java的初学者,这是我的第一篇文章

1 个答案:

答案 0 :(得分:2)

  

例如,当我把Alina,[A]没关系,[l]和Alina,然后我把马克,我淹没[l]到&#34; a&#34;和Alina to&#34; Mark&#34;。只有[A]会留下[M]

错误在于for循环:

for (String keys : words.keySet()) {
    jTextArea1.append("[" + keys + "]\n");            
    for (String keyss : firstLevel.keySet()) { // <-- Here
        jTextArea1.append("        " + "[" + keyss + "]\n");                
        for (String keysss : secondLevel) { // <-- Here
            jTextArea1.append("           " + "-" + keysss + "\n");
        }
    }
}

您应该遍历地图并列出相应的条目,而不是迭代firstLevelsecondLevel(您刚才定义的):

(我在这里使用Map.forEach,因为它更简洁一点)

words.forEach((c1, map) -> {
    jTextArea1.append("[" + c1 + "]");

    map.forEach((c2, list) -> {
        jTextArea1.append("        " + "[" + c2 + "]");

        list.forEach(name -> jTextArea1.append("           " + "-" + name));
    });         
});