Results 1 to 3 of 3
  1. #1
    JC_Drumcondra is offline Member
    Join Date
    Apr 2011
    Posts
    1
    Rep Power
    0

    Default From Map to List

    I'm working with a Map, and i'm trying to pass the values of a Map as the elements for the creation of a new list. I have tried various ways so far, but to no avail. I suspect i maybe missing the obvious.

    List<someObject> holder = new ArrayList<someObject>();
    holder.addAll(this.someMap.values());

    Instance Variable Declaration;
    Map <String, List<someObject> someMap;

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,450
    Rep Power
    18

    Default

    Your addAll() expects a List<someObject>.
    Your values() is returning a List<List<someObject>>. So they're not compatible.
    You'll have to loop round the values() and addAll() each individual List<someObject>.

    ETA: Sorry, that should be Collection<List<someObject>>, but the point still stands.

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,000
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by JC_Drumcondra View Post
    I'm working with a Map, and i'm trying to pass the values of a Map as the elements for the creation of a new list. I have tried various ways so far, but to no avail. I suspect i maybe missing the obvious.

    List<someObject> holder = new ArrayList<someObject>();
    holder.addAll(this.someMap.values());

    Instance Variable Declaration;
    Map <String, List<someObject> someMap;
    You Map contains String elements as keys as List<someObject> elements as associated values. Do you want to 'flatten' all those lists in one big list? If so, view the Map as an entrySet() and add all the values (those are the lists) to your final list. Or create a values() collection and iterate over it and do the same with each element:

    Java Code:
    for (List<someObject> value : yourMap.values())
       yourList.addAll(value);
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Replies: 8
    Last Post: 11-04-2011, 08:30 PM
  2. Ordered list - inserting wherever on the list
    By Mnem in forum New To Java
    Replies: 6
    Last Post: 01-10-2011, 12:21 PM
  3. Replies: 2
    Last Post: 11-22-2009, 05:24 PM
  4. Replies: 3
    Last Post: 11-21-2009, 05:48 PM
  5. how to create list of list in java ???
    By ilayaraja in forum Advanced Java
    Replies: 1
    Last Post: 10-26-2009, 04:30 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •