reference http://www.ne.jp/asahi/hishidama/home/tech/java/stream.html
List.forEach
List<Integer> list = Arrays.asList(1,2,3);
list.forEach(System.out :: println);
This is the same as
```
List<Integer> list = Arrays.asList(1,2,3);
for(int i: list){
System.out.println(i);
}
```
1. Map.forEach
```
Map<Integer,String> map = new HashMap<>();
map.put(1,"a");
map.put(2,"b");
map.forEach((k,v) -> System.out.println(v));
```
This is the same as
```
Map<Integer,String> map = new HashMap<>();
map.put(1,"a");
map.put(2,"b");
for(Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getValue());
}
```
Frequent
Create Map from Stream.collect (Collectors.toMap ()) List
```
class Employee {
private int id;
private String name;
public Employee(int id,String name){
this.id = id;
this.name = name;
}
public int getId() {
return this.id;
}
public String getName() {
return this.name;
}
}
List<Employee> list = Arrays.asList(new Employee(1,"Sato"),new Employee(2,"large tree"),new Employee(3,"Tanaka"));
Map<Integer,String> map = lists.stream().collect(Collectors.toMap(Employee::getId,Employee::getName));
```
Process in Stream.map () List
```
List<Integer> list = Arrays.asList(1,2,3);
List<Integer> list2 = list.stream().map(i -> i * 2).collect(Collectors.toList());
```
Stream.filter () Narrow down
```
List<Integer> list = Arrays.asList(1,2,3);
list.stream().filter(i -> i < 3).forEach(System.out :: println);
```
Stream.sorted Sort
```
List<Integer> list = Arrays.asList(1,3,2);
list.stream().sorted(Comparator.comparing(i -> i)).forEach(System.out :: println);
```
Use so well
Stream.of () Stream creation
```
Stream<Integer> stream = Stream.of(1,2,3);
```
Stream.anyMatch () Check if there is matching data
```
List<Integer> list = Arrays.asList(1,2,3);
boolean m = list.stream().anyMatch(i -> i == 2);
```
Similar to the above are allMatch (all values match) and noneMatch (all values do not match).
List.stream (). FlatMap (l-> l.stream ()) Combine Lists in List into one
```
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2,3),Arrays.asList(4,5,6));
List<Integer> list2 = list.stream().flatMap(l -> l.stream()).collect(Collectors.toList());
```
Recommended Posts