JuniorDev
JuniorDev

Reputation: 31

How can I access the value in ArrayList<LinkedHashMap<K,V>>?

There are 3 values in LinkedHashMap.

"id" ->1
"name"->A
"status"->ACTIVE

But I can't access them via arraylist.

enter image description here

How can I access the id value?

Upvotes: 0

Views: 45

Answers (1)

koZmiZm
koZmiZm

Reputation: 59

Did you intialize the ArrayList? Like, did you add an element to it first?

import java.util.ArrayList;
import java.util.LinkedHashMap;

public class StackOverflow {
    
    public static void main(String[] args) {
        ArrayList<LinkedHashMap<String, String>> myList = new ArrayList<>();
        myList.add(new LinkedHashMap<>());//
        myList.get(0).put("id", "1");
        myList.get(0).put("name", "A");
        myList.get(0).put("status", "ACTIVE");
        
        //now you should be able to access them using  
        System.out.println( myList.get(0).get("id") );
    }   
    
}

If you want a special function called getID(), you will have to code that yourself. Also, I agreee with other comments that it seems like you should be creating a class. I'm not even sure what return types those are. Seems like they are mixed. I made them into String, but I'm betting you need to make a class that has 3 properties. id, name, status

Here is a basic example of a record class that holds those 3 properties

import java.util.ArrayList;

public class StackOverflow {
    
    enum Status { ACTIVE, INACTIVE } 
    record Person(long id, String name, Status status) { }

    public static void main(String[] args) {
        ArrayList<Person> myList = new ArrayList<>();
        myList.add(new Person(1L, "A", Status.ACTIVE));
        
        //now you should be able to access them using  
        System.out.println( myList.get(0).id() );
        System.out.println( myList.get(0).name() );
        System.out.println( myList.get(0).status() );
    }   
}

Upvotes: 0

Related Questions