Most efficient way to split List<Object > into List<String>
Hi all I am using JPA and have queries like this one below:
Select emp.aid, emp.surname from employees emp
The query stores the records in the
List<Object > list.
If emp.aid is a long integer and emp.surname is a String, what is the most efficient way to get two lists from the result. One a
List<Integer> and the second
The order in both must stay in sync during the splitting process. What is the most efficient way performance wise to go this?
I wouldn't have two lists that have associated elements, rather create an
Employeeclass with two fields (
surname) and instead of storing each record returned from the query into a
Objectconstruct a new
Employeeobject for each record returned providing the appropriate data.
This way you don't even need to deal with the complexity of dealing with
List<Object>and then ensuring that when this is split into two lists of different types that also each
idof the Integer list must but at the same position as the
namein the String list.
However, if you wish to proceed with your current approach you can do something like:
List<Integer> idList = tempList.stream() .map(e -> (Integer)e).collect(Collectors.toList());
and the corresponding names:
List<String> nameList = tempList.stream() .map(e -> (String)e).collect(Collectors.toList());
tempListis defined as