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 List<String>

The order in both must stay in sync during the splitting process. What is the most efficient way performance wise to go this?

1 answer

  • answered 2017-11-12 20:10 Aomine

    I wouldn't have two lists that have associated elements, rather create an Employee class with two fields (id, surname) and instead of storing each record returned from the query into a Object[] construct a new Employee object 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 id of the Integer list must but at the same position as the name in the String list.

    However, if you wish to proceed with your current approach you can do something like:

    List<Integer> idList =                                   
                                   .map(e -> (Integer)e[0]).collect(Collectors.toList());

    and the corresponding names:

    List<String> nameList =                                  
                                    .map(e -> (String)e[1]).collect(Collectors.toList());

    where tempList is defined as List<Object[]> tempList.