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 ?
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.
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
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.
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.
You can chain as many intermediate operations as you please...
class1List.stream()
.map(Class1::getClass2)
.map(Class2::getId)
.collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With