fork(12) download
  1. import java.util.*;
  2. import java.lang.*;
  3. import java.io.*;
  4. import java.util.stream.*;
  5.  
  6. class Java8ConversionExamples
  7. {
  8. public static void main (String[] args) throws java.lang.Exception
  9. {
  10. //1 Convert `List<String>` to `List<Integer>`
  11. List<String> l1 = Arrays.asList("1", "2", "3");
  12. List<Integer> r1 = l1.stream().map(Integer::parseInt).collect(Collectors.toList());
  13. System.out.println("1: " + r1);
  14.  
  15. //2 Convert `List<String>` to `int[]`
  16. int[] r2 = l1.stream().mapToInt(Integer::parseInt).toArray();
  17. System.out.println("2: " + Arrays.toString(r2));
  18.  
  19. //3 Convert `String[]` to `List<Integer>`
  20. String[] a1 = {"4", "5", "6"};
  21. List<Integer> r3 = Stream.of(a1).map(Integer::parseInt).collect(Collectors.toList());
  22. System.out.println("3: " + r3);
  23.  
  24. //4 Convert `String[]` to `int[]`
  25. int[] r4 = Stream.of(a1).mapToInt(Integer::parseInt).toArray();
  26. System.out.println("4: " + Arrays.toString(r4));
  27.  
  28. //5 Convert `String[]` to `List<Double>`
  29. List<Double> r5 = Stream.of(a1).map(Double::parseDouble).collect(Collectors.toList());
  30. System.out.println("5: " + r5);
  31.  
  32. //6 (bonus) Convert `int[]` to `String[]`
  33. int[] a2 = {7, 8, 9};
  34. String[] r6 = Arrays.stream(a2).mapToObj(Integer::toString).toArray(String[]::new);
  35. System.out.println("6: " + Arrays.toString(r6));
  36. }
  37. }
Success #stdin #stdout 0.09s 320832KB
stdin
Standard input is empty
stdout
1: [1, 2, 3]
2: [1, 2, 3]
3: [4, 5, 6]
4: [4, 5, 6]
5: [4.0, 5.0, 6.0]
6: [7, 8, 9]