convert comma separated string to list without intermediate container

前端 未结 7 2027
误落风尘
误落风尘 2021-01-01 12:36

I need to convert comma separated string to list of integers. For example if I have following string

String numbersArray = \"1, 2, 3, 5, 7, 9,\";


        
相关标签:
7条回答
  • 2021-01-01 13:26

    If you're not on java8, then you can use Guava

    Lists.transform(Arrays.asList(numbersArray.split(",")), new Function<String, Integer>() {
                        @Override
                        public Integer apply(String input) {
                            return Integer.parseInt(input.trim());
                        }
                    });
    

    As @Maroun has mentioned for Java8 you can use Streams.

    int[] numbers = Arrays.asList(numbersArray.split(","))
                          .stream()
                          .map(String::trim)
                          .mapToInt(Integer::parseInt).toArray();
    
    0 讨论(0)
提交回复
热议问题