简体   繁体   中英

ArrayList get all values for an object property

Lets say I have an ArrayList of a object User so ArrayList<user> . A User object has a property userID .

Rather than iterating the list myself and adding userIDs to a separate list, is there and API call where I could pass it the property I want on that object and have a list of these properties returned to me? Had a look through the API and nothing stood out.

Looking for a solution in Java 7 or <.

You can do this using lambdas expressions (Java 8) :

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

public class Test {
  public static void main(String args[]){
    List<User> users = Arrays.asList(new User(1,"Alice"), new User(2,"Bob"), new User(3,"Charlie"), new User(4,"Dave"));
    List<Long> listUsersId = users.stream()
                                  .map(u -> u.id)
                                  .collect(Collectors.toList());
    System.out.println(listUsersId);
  }
}

class User {
  public long id;
  public String name;

  public User(long id, String name){
    this.id = id;
    this.name = name;
  }
}

Output :

[1, 2, 3, 4]

Snippet here .


Ugliest solution using reflection :

[1, 2, 3, 4]

Output :

 [1, 2, 3, 4] 

You can use Guava's Collections2#transform method to have the same result.

List<Integer> userIDs = Collections2.transform(users, new Function<User, Integer> (){
                            public Integer apply(User user) {
                                   return user.getUserID();
                            }
                        });

Guava supports Java 7 and lower, so if you want to use an external library, the above will work in your case.

Unfortunately, you will have to do similar logic for any other objects and their inner fields you might have. It's not as a generic solution as the reflection one, it's just a more compact one.

It sounds like you want to use a Map .

Maps use a Key, Value pair. You can assign the userID as the key and the actual user object as the value.

You can read more here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM