-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?

Eran
  • 387,369
  • 54
  • 702
  • 768
Shakib Karami
  • 678
  • 1
  • 4
  • 11
  • add an exemple of data, because it's not clear what are asking for, add what you did so far – Oussema Aroua Dec 13 '18 at 09:42
  • Possible duplicate of [Java - map a list of objects to a list with values of their property attributes](https://stackoverflow.com/questions/737244/java-map-a-list-of-objects-to-a-list-with-values-of-their-property-attributes) – Tom Dec 13 '18 at 09:45

1 Answers1

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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768