Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a list of specific fields values from objects stored in a list?

Say I have an list of objects with two fields field1 and field2, both of String type.

How do I get a list of all field1 values without having to iterate over the list, if it is at all possible?

like image 400
user1343585 Avatar asked Jun 12 '12 12:06

user1343585


People also ask

How do I get a list of fields from a list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.


2 Answers

Fortunately, you can do this using Java 8 - Streams

Assume you have an entity named YourEntity

public class YourEntity {      private String field1;     private String field2;      public YourEntity(String field1, String field2) {         this.field1 = field1;         this.field2 = field2;     }      public void setField1(String field1) {         this.field1 = field1;     }      public void setField2(String field2) {         this.field2 = field2;     }      public String getField1() {         return field1;     }      public String getField2() {         return field2;     } } 

Declare you list of YourEntity using:

List<YourEntity> entities = Arrays.asList(new YourEntity("text1", "text2"), new YourEntity("text3", "text4")); 

You can extract the list of field1 in one shot in this way:

import java.util.stream.Collectors;  List<String> field1List = entities.stream().map(YourEntity::getField1).collect(Collectors.toList()); 

Or in this way

import java.util.stream.Collectors;  List<String> field1List = entities.stream().map(urEntity -> urEntity.getField1()).collect(Collectors.toList()); 

You can print all the items also using java 8 :)

field1List.forEach(System.out::println); 

Output

text1 text3 
like image 165
Jad Chahine Avatar answered Sep 30 '22 14:09

Jad Chahine


try this:

List<Entity> entities = getEntities(); List<Integer> listIntegerEntities = Lambda.extract(entities, Lambda.on(Entity.class).getFielf1()); 

the LambdaJ allows to access collections without explicit loops, so instead of have more lines of code to iterate the list yourself, you let LambdaJ do it.

like image 23
Euclides Mulémbwè Avatar answered Sep 30 '22 12:09

Euclides Mulémbwè