Results 1 to 2 of 2
Like Tree1Likes
  • 1 Post By jim829

Thread: How to pass a Map.Entry<K, V> to a List<Map.Entry<K, V>>

  1. #1
    ghandil is offline Member
    Join Date
    Jun 2013
    Posts
    28
    Rep Power
    0

    Default How to pass a Map.Entry<K, V> to a List<Map.Entry<K, V>>

    Hi,
    There's a List like this:
    Java Code:
    List<Map.Entry<Object, String>> list = new ArrayList<>();
    I need to add elements to this list through a for loop. but below syntax gives an error:
    Java Code:
    list.add(Map.Entry<o, text>);
    Error:
    Expression expected


    Edit: I used the way to implement Map.Entry<> (described here) to make new Map entries. but I jest wondered if there's better way while the Entry is adding through the List interface.

    The code of implemented Map.Entry in the above link and its usge in adding an entry to the list:

    Java Code:
    import java.util.Map;
    
    final class MyEntry<K, V> implements Map.Entry<K, V> {
        private final K key;
        private V value;
    
        public MyEntry(K key, V value) {
            this.key = key;
            this.value = value;
        }
    
        @Override
        public K getKey() {
            return key;
        }
    
        @Override
        public V getValue() {
            return value;
        }
    
        @Override
        public V setValue(V value) {
            V old = this.value;
            this.value = value;
            return old;
        }
    }
    
    
    list.add( new MyEntry<>(o, text));

    Thanks
    Last edited by ghandil; 03-07-2016 at 09:41 AM.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: How to pass a Map.Entry<K, V> to a List<Map.Entry<K, V>>

    Quote Originally Posted by ghandil View Post
    but I jest wondered if there's better way while the Entry is adding through the List interface.
    There is no better way to do it. The list holds individual items but an key/value pair is two items. So you need to wrap them.
    If you simply wanted to grab an existing list of entries and put them in a list, then you might consider using the
    HashMap.entrySet<> method.

    Regards,
    Jim
    ghandil likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 3
    Last Post: 12-20-2013, 09:17 PM
  2. Replies: 10
    Last Post: 02-11-2011, 09:15 PM
  3. Entry in table
    By Harsh_Verma in forum New To Java
    Replies: 2
    Last Post: 07-01-2009, 03:07 PM
  4. Need Help On Entry Validation
    By obdi in forum New To Java
    Replies: 3
    Last Post: 07-25-2008, 07:39 AM

Posting Permissions

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