Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

java - How to get values and keys from HashMap?

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:

HashMap<String, Tab> hash = new HashMap<String, Tab>();

Where Tab will receive the values, such as: File file, JTextArea container, JTabbedPane tab.

I have a class called Tab:

public Tab(File file, JTextArea container, JTabbedPane tab)
{
    this.file = file;
    this.container = container;
    this.tab = tab;
    tab.add(file.getName(), container);
    readFile();
}

Now, in this SaveFile class, I need get the Tab values stored in the HashMap. How can I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To get all the values from a map:

for (Tab tab : hash.values()) {
    // do something with tab
}

To get all the entries from a map:

for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
    String key = entry.getKey();
    Tab tab = entry.getValue();
    // do something with key and/or tab
}

Java 8 update:

To process all values:

hash.values().forEach(tab -> /* do something with tab */);

To process all entries:

hash.forEach((key, tab) -> /* do something with key and tab */);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...