The Stream.collect() Method
Tags: programming
Published: 2023-04-14 01:12:21

##The Stream.collect() Method

```java 
List<Integer> numberList = Arrays.asList(11, 3, 2, 3, 8, 9, 0, 7, 2);
numberList.stream().collect(Collectors.toSet());

```
Collect metodu Stream türündeki nesneleri başka biçimdeki nesneye, veri yapısına dönüştürmek için kullanılır. **Collector** arayüzünden türeyen bir parametre beklemektedir. Bu parametre bilgisi ile istenilen türe dönüşüm sağlanabilir. Collector türünden arayüzler **Collectors** sınıfının içinde bulunan metodlar ile elde edilebilir.

## Collector Interface

-  yeni bir sonuç containerının  oluşturulması (supplier())
-  yeni bir elemanı sonuc containerına dahi etme (accumulator())
-   iki sonuç containerını bir araya getirmek (combiner())
-   containerda isteğe bağlı bir son dönüşüm gerçekleştirme (finisher())

## .Collect(Collectors.) örnekleri

List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");

- toList()
```java
List<String> result = givenList.stream().collect(toList());
```

- Collectors.toUnmodifiableList()
```java
List<String>result=givenList.stream()
.collect(toUnmodifiableList());
```
- toSet()
```java
Set<String> result = givenList.stream()
.collect(toSet());
```
- Collectors.toUnmodifiableSet()
```java
Set<String> result = givenList.stream()
.collect(toUnmodifiableSet());
```
- Collectors.toCollection()
```java
List<String> result = givenList.stream()
.collect(toCollection(LinkedList::new))
```

- Collectors.toMap()
```java
Map<String, Integer> result = givenList.stream()
.collect(toMap(Function.identity(), String::length))
```

identity fonksiyonu
```java
static <T> Function<T, T> identity() {
        return t -> t;
 ```

duplicate bir veri gelirse 

```java
List<String> listWithDuplicates = 
Arrays.asList("a", "bb", "c", "d", "bb"); assertThatThrownBy(
() -> { listWithDuplicates.stream()
.collect(toMap(Function.identity(), String::length)); })
.isInstanceOf(IllegalStateException.class);
```

 çözümü

```java
 Map<String, Integer> result = 
givenList.stream()
.collect(toMap(Function.identity(),
 String::length,
(item, identicalItem) -> item));
 ```

- Collectors.toUnmodifiableMap()
```java
Map<String, Integer> result = givenList.stream()
.collect(toUnmodifiableMap(Function.identity(),
String::length))
```
- Collectors.collectingAndThen()
```java 
List<String> result = givenList.stream()
.collect(collectingAndThen(toList(), ImmutableList::copyOf))

```

- Collectors.joining()
```java
String result = givenList.stream(joining());

```
>"abbcccdd"


```java
String  result  = givenList.stream()
.collect(joining(" "));
```
>"a bb ccc dd"


```java
String  result  = givenList.stream()
.collect(joining(" ", "PRE-", "-POST"));

```
>"PRE-a bb ccc dd-POST"


- Collectors.counting()
```java
Long result = givenList.stream()
  .collect(counting());
  ```

- Collectors.summarizingDouble/Long/Int()
```java
DoubleSummaryStatistics  result  = givenList.stream()
.collect(summarizingDouble(String::length));

  ```
  > assertThat(result.getAverage()).isEqualTo(2); assertThat(result.getCount()).isEqualTo(4); assertThat(result.getMax()).isEqualTo(3); assertThat(result.getMin()).isEqualTo(1); assertThat(result.getSum()).isEqualTo(8);
  

- Collectors.maxBy()/minBy()
```java 
Optional<String> result = givenList.stream()
.collect(maxBy(Comparator.naturalOrder()));
 ```
 - Collectors.groupingBy()
```java
Map<Department, List<Employee>> byDept =
employees.stream()
.collect(Collectors.
groupingBy(Employee::getDepartment));
```
 ```java 
 Map<Integer, Set<String>> result = givenList.stream()
.collect
(groupingBy(String::length, toSet()));
  ```
 ```java 
Map<Department, Integer> totalByDept  = employees.stream()
.collect(Collectors
.groupingBy(Employee::getDepartment
.Collectors.summingInt(Employee::getSalary)));
```

- Collectors.partitioningBy()

```java 
Map<Boolean, List<String>> result =
givenList.stream()
.collect(partitioningBy(s -> s.length() > 2))
```
>{false=["a", "bb", "dd"], true=["ccc"]}

 ```java 
Map<Boolean, List<Student>> passingFailing =
students.stream().collect(Collectors
.partitioningBy
(s -> s.getGrade() >= PASS_THRESHOLD));

```

- Collectors.teeing()

 ```java 
List<Integer> numbers = Arrays.asList(42, 4, 2, 24);

Optional<Integer> min =
numbers.stream().collect(minBy(Integer::compareTo)); 

Optional<Integer> max =
numbers.stream().collect(maxBy(Integer::compareTo));
```
--java 12 sonrası 
 ```java 
numbers.stream()
.collect(teeing( minBy(Integer::compareTo),
maxBy(Integer::compareTo),
(min, max) ->
));

```
 ```java 	
HashMap<String, Employee> result =
employeeList.stream().collect(Collectors.teeing(
Collectors.maxBy(Comparator.
comparing(Employee::getSalary)).

Collectors.minBy(Comparator.
comparing(Employee::getSalary)),
 (e1, e2) -> {
  HashMap<String, Employee> map = new HashMap();
  map.put("MAX", e1.get());
  map.put("MIN", e2.get());
  return map;
  }
 ));
```