Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a new list with a property of an object which is in another list

Imagine that I have a list of certain objects:

List<Student> 

And I need to generate another list including the ids of Students in the above list:

List<Integer> 

Avoiding using a loop, is it possible to achieve this by using apache collections or guava?

Which methods should be useful for my case?

like image 235
javatar Avatar asked Jun 11 '12 07:06

javatar


People also ask

How do you combine two lists of objects?

One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.

Can you add an object to a List?

Yes, but you must work with the former account object, otherwise you will override the reference when assigning a new object.

How do you add all elements of a List to another List in Java?

It is possible to add all elements from one Java List into another List . You do so using the List addAll() method. The resulting List is the union of the two lists.


1 Answers

Java 8 way of doing it:-

List<Integer> idList = students.stream().map(Student::getId).collect(Collectors.toList()); 
like image 75
Kaushik Avatar answered Oct 02 '22 12:10

Kaushik