Skip to content

Commit

Permalink
feat: How to convert Array to Stream.
Browse files Browse the repository at this point in the history
  • Loading branch information
danielso2007 committed Dec 20, 2019
1 parent 35b81b3 commit c707017
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package br.com.somejava8examples.streams;

import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@Service
public class HowToConvertArrayToStreamService {

public void objectArrays() {
String[] array = {"a", "b", "c", "d", "e"};

//Arrays.stream
Stream<String> stream1 = Arrays.stream(array);
stream1.forEach(x -> System.out.println(x));

//Stream.of
Stream<String> stream2 = Stream.of(array);
stream2.forEach(x -> System.out.println(x));
}

public void primitiveArrays() {
int[] intArray = {1, 2, 3, 4, 5};

// 1. Arrays.stream -> IntStream
IntStream intStream1 = Arrays.stream(intArray);
intStream1.forEach(x -> System.out.println(x));

// 2. Stream.of -> Stream<int[]>
Stream<int[]> temp = Stream.of(intArray);

// Cant print Stream<int[]> directly, convert / flat it to IntStream
IntStream intStream2 = temp.flatMapToInt(x -> Arrays.stream(x));
intStream2.forEach(x -> System.out.println(x));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package br.com.somejava8examples.stream;

import br.com.somejava8examples.streams.HowToConvertArrayToStreamService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("test")
public class HowToConvertArrayToStreamTest {

@Autowired
private HowToConvertArrayToStreamService service;

@Test
public void objectArraysTest() {
service.objectArrays();
}

@Test
public void primitiveArraysTest() {
service.primitiveArrays();
}

}

0 comments on commit c707017

Please sign in to comment.