---
title: "Stream - Map"
author: "fairy_xzc"
date: "2018-06-19T21:46:18Z"
tags: []
categories: ["编程语言"]
slug: "stream-map"
draft: false
lastmod: "2018-06-19T21:48:02Z"
id: 2425203
url: "https://agilestyle.iteye.com/blog/2425203"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2425203](/blog/2425203)**

 

## map

```
private static void mapTest() {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7);

    List<Integer> result = list.stream().map(i -> i * 2).collect(Collectors.toList());

    System.out.println(result);
}
```

Console Output

```
[2, 4, 6, 8, 10, 12, 14]
```

  

## flatMap

```
private static void flatMapTest() {
    String[] words = {"Hello", "World"};

//        Stream<String> stream = Arrays.stream(words);
//        Stream<String[]> stream1 = stream.map(w -> w.split(""));
//        Stream<String> stringStream = stream1.flatMap(Arrays::stream);
//        stringStream.distinct().forEach(System.out::println);

    Arrays.stream(words).map(w -> w.split("")).flatMap(Arrays::stream).distinct().forEach(System.out::print);
}
```

Console Output

```
HeloWrd
```

**Using flatMap to find the unique characters from a list of words**  

![](http://dl2.iteye.com/upload/attachment/0130/0896/bf610625-648a-32f0-9b14-0000018351dc.png)  
 

## Reference

Manning.Java.8.in.Action.Lambdas.Streams.and.functional-style.programming