Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to List<Long>

Tags:

java

I have a string with comma separated value that I am getting direclty from database. Now I want to pass that entire string to another query but the datatype required is long and i want to use in clause to get this done.

str1 = [123,456,789];

Is there any direct way to do it instead of looping.

like image 323
user2986404 Avatar asked Nov 13 '13 06:11

user2986404


2 Answers

A little shorter than virag's answer, as it skips asList() and doesn't do a string trim.

List<Long> list = Arrays.stream(str.split(",")).map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
like image 186
Bienvenido David Avatar answered Oct 04 '22 02:10

Bienvenido David


You can use the Lambda functions of Java 8 to achieve this without looping

    String string = "1, 2, 3, 4";
    List<Long> list = Arrays.asList(string.split(",")).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
like image 27
virag Avatar answered Oct 04 '22 04:10

virag