Reputation: 21
I have an arraylist brotherLists which stores values as object.Object's properties are firstname,occupation,genderand id.I also have a map Relatives in which I put this array list,as you can see below.
List brothersList=new ArrayList<Object>();
brothersList.add(brother1);
brothersList.add(brother2);
this.getRelatives().put("brother", brothersList);
How can I print individual properties(firstname,Occupation etc..) of an object in this arraylist which is now in a map.thanks
Upvotes: 2
Views: 68
Reputation: 18072
Say you wanted to print all names for your brothers array you could do this:
for(Entry<String, List> i : brothersList().entrySet()){
List item = i.getValue();
for(Object j : item){
System.out.println(j.firstName); //or use your getter method
}
}
If you want to get a single item you can do this:
List brothersList = brothersList().get("brothers");
Object brother1 = brothersList.get(0); //get by index
String brother1Name = brother1.firstName;
If you wanted to get a brother by searching, say, by their name. You would need an additional method which scans through array and finds match i.e.:
public String findOccupation(String name){
List brothersList = brothersList().get("brothers");
for(Object brother : brothersList){
if(brother.firstName.equals(name){
return brother.occupation;
}
}
}
Usage:
System.out.print(findOccupation("Ajay"));
Output:
Programmer
Upvotes: 2
Reputation: 9049
If you want to access the list you just stored in the map, and iterate on it printing the information for each element, you can do:
for (Object person : this.getRelatives().get("brother")) {
System.out.println(person);
}
The method Map.get()
accepts a key and retrieves the value associated with it that was previously stored in the map.
There seems to be no reason for your list to be a List<Object>
. Also, you should not declare the variable brothersList
simply as List
, without saying which type it contains.
Assuming the name of your custom class is Person
, you should create a List<Person>
like this:
List<Person> brothers = new ArrayList<>();
This way, you will be able to access specific Person
methods when you iterate on the list contents.
To print the individual properties of the Person
objects, remember you need to override the method toString()
:
class Person {
...
@Override
public String toString() {
return this.firstname + ", " + this.occupation;
}
}
Upvotes: 0