Java 8 join lists


public class CollectionsJoinWithJava8 {

    @Test
    public void shouldJoinLists() {
        List<Integer> result = Arrays.asList(1,2,3)
            .parallelStream()
            .flatMap(count -> find(count).stream())
            .collect(Collectors.toList());

        assertEquals(Arrays.asList(0, 0, 1, 0, 1, 2), result);
    }

    @Test
    public void shouldJoinLists2() {
        List<Integer> result = new ArrayList<Integer>();
        for (Integer count : Arrays.asList(1,2,3)) {
            List<Integer> find = find(count);
            result.addAll(find);
        }

        assertEquals(Arrays.asList(0, 0, 1, 0, 1, 2), result);
    }

    private List<Integer> find(int i) {
        List<Integer> list = new ArrayList<Integer>();
        for (int j = 0; j < i; j++) {
            list.add(j);
        }
        return list;
    }

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s