Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert multiple attributes of object into List<String> using java 8

I am wondering if there is a way to combine multiple attributes from an object into a list of String. In My Case, I have an object with the name "debitCardVO" and I want it to convert from object to List

Here is my code Snippet:

for (DebitCardVO debitCardVO : debitCardVOList) {
    List<String> debitCardList   = debitCardVOList.stream()
            .map(DebitCardVO::getCardBranchCode,DebitCardVO::getAccountNo)
            .collect(Collectors.toList());
}
like image 666
Jawad Tariq Avatar asked Feb 07 '19 11:02

Jawad Tariq


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.

Which method is used to convert an object to List?

Correct Option: B. singletonList() returns the object as an immutable List. This is an easy way to convert a single object into a list.

Can we convert object to List in Java?

//Assuming that your object is a valid List object, you can use: Collections. singletonList(object) -- Returns an immutable list containing only the specified object. //Similarly, you can change the method in the map to convert to the datatype you need.


Video Answer


1 Answers

flatMap can help you flatMap vs map

List<String> debitCardList = debitCardVOList.stream()
                    .flatMap(d -> Stream.of(d.getCardBranchCode(),d.getAccountNo()))
                    .collect(Collectors.toList());

Other examples here

like image 102
David Pérez Cabrera Avatar answered Oct 20 '22 13:10

David Pérez Cabrera