-2

I have an ArrayList(Hashmap<String, String>) named users and each Hashmap<String, String> contains the profile of a user such as name,id,phone, etc...

I want to convert this ArrayList into some simple ArrayList. For example, I want to have an id ArrayList that contains all ids that can be found in the main ArrayList. Is there any function to do that?

2

1 Answer 1

2

You can write such a function with Streams:

public static List<String> getPropertyList(List<Map<String,String>> users, String key)
{
    return users.stream()
                .map(m -> m.get(key))
                .collect(Collectors.toList());
}

Then call it with:

List<String> userIds = getPropertyList(users,"id");
List<String> userNames = getPropertyList(users,"name");
...

P.S. I changed the type of the list from ArrayList<HashMap<String,String>> to List<Map<String,String>>, since it's better to program to interfaces.

If you are using Java 7 or older, you'll need a loop:

public static List<String> getPropertyList(List<Map<String,String>> users, String key)
{
    List<String> result = new ArrayList<String>();
    for (Map<String,String> map : users) {
        result.add(map.get(key));
    }
    return result;
}
Sign up to request clarification or add additional context in comments.

3 Comments

thanks a lot man but it seems this code requires 1.8 version of java, can you edit that part that requires java1.8?
the line is 'm -> m.get(key)'
@ShakibKarami ok, I just did

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.