配列、ストリーム、コレクションの変換 ~ int編 ~

2023/03/29に公開

チートシート

扱うもの

  • 配列
    • int[]
    • Integer[]
  • ストリーム
    • IntStream
    • Stream<Integer>
  • コレクション
    • List<Integer>
    • Set<Integer>

int[] -> IntStream

int[] arr = new int[]{1,2,3};
// その1 
IntStream intStream = IntStream.of(arr);
// その2
IntStream intStream = Arrays.stream(arr);

IntStream -> int[]

IntStream intStream = IntStream.of(1,2,3);
int[] arr = intStream.toArray();

IntStream -> Stream<Integer>

IntStream intStream = IntStream.of(1,2,3);
Stream<Integer> intStream.boxed();

Stream<Integer> -> IntStream

Stream<Integer> stream = Stream.of(1,2,3);
IntStream intStream = stream.mapToInt(Integer::intValue);

Stream<Integer> -> Integer[]

Stream<Integer> stream = Stream.of(1,2,3);
Integer[] arr = stream.toArray(Integer[]::new);

Integer[] -> Stream<Integer>

Integer[] arr = new Integer[]{1,2,3};
// その1
Stream<Integer> stream = Stream.of(arr);
// その2
Stream<Integer> stream = Arrays.stream(arr);

List<Integer> -> Stream<Integer>

List<Integer> list = Arrays.asList(1,2,3);
Stream<Integer> stream = list.stream();

Stream<Integer> -> List<Integer>

Stream<Integer> stream = Stream.of(1,2,3);
List<Integer> list = stream.collect(Collectors.toList());

Stream<Integer> -> Set<Integer>

Stream<Integer> stream = Stream.of(1,2,3);
Set<Integer> set = stream.collect(Collectors.toSet());

Set<Integer> -> Stream<Integer>

Set<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));
Stream<Integer> stream = set.stream();

List<Integer> -> Set<Integer>

List<Integer> list = Arrays.asList(1,2,3);
Set<Integer> set = new HashSet<Integer>(list);

Set<Integer> -> List<Integer>

Set<Integer> set = new HashSet<Integer>(Arrays.asList(1,2,3));
List<Integer> list = new ArrayList<Integer>(set)

List<Integer> -> Integer[]

List<Integer> list = Arrays.asList(1,2,3);
Integer[] arr = list.toArray(new Integer[0]);

Integer[] -> List<Integer>

Integer[] arr = new Integer[]{1,2,3};
List<Integer> list = Arrays.asList(arr);

Discussion