How to get value from TreeMap in Java?

19,016

With this code that you have:

String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);

You are getting all keys from the map. If you want all values, then use:

library.values();

Finally, if you need to get a value by key use V get(Object key):

library.get("01");

Which will return you the first Item from the map.

It's not very clear which one of these you want, but basically these are the options.

** EDIT **

Since you want all values you can do this:

library.values().toArray()

JList expects an array or vector of Object so this should work.

Share:
19,016
rewen
Author by

rewen

Updated on June 30, 2022

Comments

  • rewen
    rewen almost 2 years

    My problem is can't get an object "Item" (value) from my Treemap. I need send that info to my GUI class and display it in JList to get a select list, so can easily select and add songs to playlist, but only what I get as an output is "01, 02, 03, 04, 05" (key). Please help, because I'm beginner and have no idea what to do.

    public class LibraryData {
    
    private static class Item {
    
    
        Item(String n, String a, int r) {
            name = n;
            artist = a;
            rating = r;
        }
    
        // instance variables 
        private String name;
        private String artist;
        private int rating;
        private int playCount;
    
        public String toString() {
            return name + " - " + artist;
        }
    }
    
    
    private static Map<String, Item> library = new TreeMap<String, Item>();
    
    
    static {
        library.put("01", new Item("How much is that doggy in the window", "Zee-J", 3));
        library.put("02", new Item("Exotic", "Maradonna", 5));
        library.put("03", new Item("I'm dreaming of a white Christmas", "Ludwig van Beethoven", 2));
        library.put("04", new Item("Pastoral Symphony", "Cayley Minnow", 1));
        library.put("05", new Item("Anarchy in the UK", "The Kings Singers", 0));
    }
    
    
    public static String[] getLibrary() {
    String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);
    return tempa;
    }
    

    SOLUTION:

    Because I've to pass the values to another class:

    JList tracks = new JList(LibraryData.getLibrary());
    

    I made something like that and it's works

    public static Object[] getLibrary() {
    Collection c = library.values();
    return c.toArray(new Item[0]);
    

    Thank You guys, after 10 hours I finally done it! }

  • rewen
    rewen over 10 years
    I want to get each of those songs, into the JList. I was trying to change library.keySet() to library.values(), but then I get exception. The bit of code in GUI is: JList tracks = new JList(LibraryData.getLibrary());