Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a list of objects to a list of Long

I Have a class as following:

Class1 {
    private Class2 class2;
    ...
}

I want to convert a list of Class1 to a list of Class2::getId(), this is what I tried :

List<Class2> class2List = class1List.stream().map(Class1::getClass2).collect(Collectors.toList());
List<Long> class2Ids = class2List .stream().map(Class2::getId).collect(Collectors.toList());

Isn't there a way to do this in a single instruction ?

like image 442
Renaud is Not Bill Gates Avatar asked Sep 06 '18 10:09

Renaud is Not Bill Gates


People also ask

How do I turn a list of objects into strings?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

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.

How do you cast a long list?

As you want to return a list of Long, you can create a copy of the Object array to a Long array(assuming they are all of type Long) and then convert the array to a list. Save this answer.

Which can convert object into list?

4. Which of these methods can convert an object into a List? Explanation: singletonList() returns the object as an immutable List. This is an easy way to convert a single object into a list.


1 Answers

You can chain as many intermediate operations as you please...

class1List.stream()
          .map(Class1::getClass2)
          .map(Class2::getId)
          .collect(Collectors.toList());
like image 50
Eugene Avatar answered Sep 30 '22 11:09

Eugene