DEV Community 👩‍💻👨‍💻

Steve Mak
Steve Mak

Posted on

Stream

Convert n elements to an array list

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
Enter fullscreen mode Exit fullscreen mode

Stream

Stream map

List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5");

List<Integer> listOfIntegers = listOfStrings.stream()
        .map(Integer::valueOf)
        .collect(Collectors.toList());

System.out.println(listOfIntegers);
Enter fullscreen mode Exit fullscreen mode

Stream reduce

//
// Example 1
//
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
int result = numbers
  .stream()
  .reduce(0, (subtotal, element) -> subtotal + element);
assertThat(result).isEqualTo(21);

//
// Example 2 (Use method reference)
//
int result = numbers.stream().reduce(0, Integer::sum);
assertThat(result).isEqualTo(21);

//
// Example 3
//
List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35));
int result = users.stream()
  .reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum);
assertThat(result).isEqualTo(65);
Enter fullscreen mode Exit fullscreen mode

Stream.flatMap

//
// Example 1
//
Merging Lists into a Single List
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(4,5,6);
List<Integer> list3 = Arrays.asList(7,8,9);

List<List<Integer>> listOfLists = Arrays.asList(list1, list2, list3);

List<Integer> listOfAllIntegers = listOfLists.stream()
          .flatMap(x -> x.stream())
          .collect(Collectors.toList());

System.out.println(listOfAllIntegers);

//
// Example 2
//
String[][] dataArray = new String[][]{{"a", "b"}, 
        {"c", "d"}, {"e", "f"}, {"g", "h"}};

List<String> listOfAllChars = Arrays.stream(dataArray)
              .flatMap(x -> Arrays.stream(x))
              .collect(Collectors.toList());

System.out.println(listOfAllChars);
Enter fullscreen mode Exit fullscreen mode

IntStream

// Converting IntStream to Array
int[] intArray = IntStream.of(1, 2, 3, 4, 5).toArray();

// Converting IntStream to List
List<Integer> list = IntStream.of(1,2,3,4,5)
            .boxed()
            .collect(Collectors.toList());

// Returns stream containing a single specified element.
IntStream.of(10); // 10

// Returns stream containing specified all elements.
IntStream.of(1, 2, 3); // 1,2,3

// Returns a sequential ordered int stream excludes the last element.
IntStream.range(1, 5); // 1,2,3,4

// Returns a sequential ordered int stream includes the last element.
IntStream.rangeClosed(1, 5); // 1,2,3,4,5
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Create an Account! The only reason people scroll to the bottom...  
is because they want to read more.

Create an account to bookmark, comment, and react to articles that interest you.