Skip to content
Advertisement

Convert string to List

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.

Advertisement

Answer

With guava:

List<Long> longs = Lists.newArrayList(Iterables.transform(Splitter.on(',').split("1,2,3"), new Function<String, Long>() {
    public Long apply(final String in) {
        return in == null ? null : Longs.tryParse(in);
    }
}));

EDIT:

With a List<String> (stringList) as input:

List<Long> longs = Lists.newArrayList(Lists.transform(stringList, new Function<String, Long>() {
    public Long apply(final String in) {
        return in == null ? null : Longs.tryParse(in);
    }
}));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement