LoginSignup
8
5

More than 5 years have passed since last update.

JavaでStringの配列をIntegerのListに一括でcastする

Last updated at Posted at 2018-06-04

本記事のサマリ

タイトルの通りですが、例えば標準入力で空白区切りの数値群が与えられて、それをIntegerに一括で置換したいといった場合に使える小技です。
(補足ですが、Javaの場合は、java.util.ScannerのnextInt()を使うと、標準入力を直接Integerとして受け取れるので、標準入力から受け取るという文脈においてはありがたみは薄くなると思います。)

対象読者

Javaで標準入力で渡された数値群をListにする方法が知りたい方

String[]をListに変換するには

結論:streamAPIを使えばできます

以下のように、streamApiをつかって、あげると実現出来ます。
ミソとしては、map(Integer::valueOf)で、Integerに変換することと、Collectors.toList()で、最終的な結果をListにしてあげること。

Main.java
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) throws Exception {
        String[] strArray = "1 2 3 4 5".split(" ");
        for( Integer i : strArrayToIntList(strArray) ) {
            System.out.println(i * i);
        }
    }

    private static List<Integer> strArrayToIntList(String[] strArray) {
        List<Integer> intList =
          Arrays
            .stream(strArray)
            .map(Integer::valueOf)
            .collect(Collectors.toList());;
        return intList;
    }
}
8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5