How to get values and keys from HashMap?

前端 未结 10 1567
無奈伤痛
無奈伤痛 2020-12-08 01:56

I\'m writing a simple edit text in Java. When the user opens it, a file will be opened in JTabbedPane. I did the following to save the files opened:

相关标签:
10条回答
  • 2020-12-08 02:42

    You could use iterator to do that:

    For keys:

    for (Iterator <tab> itr= hash.keySet().iterator(); itr.hasNext();) {
        // use itr.next() to get the key value
    }
    

    You can use iterator similarly with values.

    0 讨论(0)
  • 2020-12-08 02:45

    With java8 streaming API:

    List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-12-08 02:48
    for (Map.Entry<String, Tab> entry : hash.entrySet()) {
        String key = entry.getKey();
        Tab tab = entry.getValue();
        // do something with key and/or tab
    }
    

    Works like a charm.

    0 讨论(0)
  • 2020-12-08 02:48

    To get values and keys you could just use the methods values() and keySet() of HashMap

    public static List getValues(Map map) {
        return new ArrayList(map.values());
    }
    
    public static List getKeys(Map map) {
        return new ArrayList(map.keySet());
    }
    
    0 讨论(0)
提交回复
热议问题