Cómo hacer una nueva lista con una propiedad de un objeto que está en otra lista


Imagine que tengo una lista de ciertos objetos:

List<Student>

Y necesito generar otra lista que incluya los id de los Estudiantes en la lista anterior:

List<Integer>

Evitando usar un bucle, ¿es posible lograr esto usando apache collectionso guava? ¿Qué métodos deberían ser útiles para mi caso?

Cualquier ayuda sería apreciada, gracias.

Author: Javatar, 2012-06-11

6 answers

Java 8 forma de hacerlo: -

List<Integer> idList = students.stream().map(Student::getId).collect(Collectors.toList());
 124
Author: Kaushik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-08 18:54:02

Con Guayaba puede usar la función como -

private enum StudentToId implements Function<Student, Integer> {
        INSTANCE;

        @Override
        public Integer apply(Student input) {
            return input.getId();
        }
    }

Y puede usar esta función para convertir la Lista de estudiantes a ids como -

Lists.transform(studentList, StudentToId.INSTANCE);

Seguramente hará un bucle para extraer todos los id, pero recuerde que los métodos de guayaba devuelven la vista y la función solo se aplicarán cuando intente iterar sobre el List<Integer>
Si no itera, nunca aplicará el bucle.

Nota: Recuerde que esta es la vista y si desea iterar varias veces, será mejor copiar el contenido en algún otro List<Integer> como

ImmutableList.copyOf(Iterables.transform(students, StudentToId.INSTANCE));
 37
Author: Premraj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 12:18:44

Gracias a Premraj por la opción alternativa cool, votada positivamente.

He usado apache CollectionUtils y BeanUtils. En consecuencia, estoy satisfecho con el desempeño del siguiente código:

List<Long> idList = (List<Long>) CollectionUtils.collect(objectList, 
                                    new BeanToPropertyValueTransformer("id"));

Vale la pena mencionar que, compararé el rendimiento de guayaba ( Premraj proporcionado) y CollectionUtils que utilicé anteriormente, y decidiré el más rápido.

 18
Author: Javatar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 16:45:33

Solución de expresión lambda Java 8:

List<Integer> iDList = students.stream().map((student) -> student.getId()).collect(Collectors.toList());
 5
Author: Vijay Gupta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-03 12:20:50

Si alguien llega aquí después de unos años:

List<String> stringProperty = (List<String>) CollectionUtils.collect(listOfBeans, TransformerUtils.invokerTransformer("getProperty"));
 2
Author: Jonathan Perrotta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-14 02:55:56

Es Matemáticamente imposible hacer esto sin un bucle. Para crear una asignación, F, de un conjunto discreto de valores a otro conjunto discreto de valores, F debe operar en cada elemento del conjunto originario. (Se requiere un bucle para hacer esto, básicamente.)

Dicho esto:

¿Por qué necesita una nueva lista? Usted podría estar abordando cualquier problema que está resolviendo de la manera equivocada.

Si tienes una lista de Student, entonces estás a solo un paso o dos de distancia, al iterar a través de esta lista, de iterar sobre los números de identificación de los estudiantes.

for(Student s : list)
{
    int current_id = s.getID();
    // Do something with current_id
}

Si tienes un problema diferente, entonces comenta/actualiza la pregunta e intentaremos ayudarte.

 -5
Author: Zéychin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-11 07:52:36