DEV Community

elifbasak
elifbasak

Posted on

The Stream.collect() Method

The Stream.collect() Method

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

Enter fullscreen mode Exit fullscreen mode

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 givenList = Arrays.asList("a", "bb", "ccc", "dd");

  • toList()
List<String> result = givenList.stream().collect(toList());
Enter fullscreen mode Exit fullscreen mode
  • Collectors.toUnmodifiableList()
List<String>result=givenList.stream()
.collect(toUnmodifiableList());
Enter fullscreen mode Exit fullscreen mode
  • toSet()
Set<String> result = givenList.stream()
.collect(toSet());
Enter fullscreen mode Exit fullscreen mode
  • Collectors.toUnmodifiableSet()
Set<String> result = givenList.stream()
.collect(toUnmodifiableSet());
Enter fullscreen mode Exit fullscreen mode
  • Collectors.toCollection()
List<String> result = givenList.stream()
.collect(toCollection(LinkedList::new))
Enter fullscreen mode Exit fullscreen mode
  • Collectors.toMap()
Map<String, Integer> result = givenList.stream()
.collect(toMap(Function.identity(), String::length))
Enter fullscreen mode Exit fullscreen mode

identity fonksiyonu

static <T> Function<T, T> identity() {
        return t -> t;
Enter fullscreen mode Exit fullscreen mode

duplicate bir veri gelirse

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

çözümü

 Map<String, Integer> result = 
givenList.stream()
.collect(toMap(Function.identity(),
 String::length,
(item, identicalItem) -> item));
Enter fullscreen mode Exit fullscreen mode
  • Collectors.toUnmodifiableMap()
Map<String, Integer> result = givenList.stream()
.collect(toUnmodifiableMap(Function.identity(),
String::length))
Enter fullscreen mode Exit fullscreen mode
  • Collectors.collectingAndThen()
List<String> result = givenList.stream()
.collect(collectingAndThen(toList(), ImmutableList::copyOf))

Enter fullscreen mode Exit fullscreen mode
  • Collectors.joining()
String result = givenList.stream(joining());

Enter fullscreen mode Exit fullscreen mode

"abbcccdd"

String  result  = givenList.stream()
.collect(joining(" "));
Enter fullscreen mode Exit fullscreen mode

"a bb ccc dd"

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

Enter fullscreen mode Exit fullscreen mode

"PRE-a bb ccc dd-POST"

  • Collectors.counting()
Long result = givenList.stream()
  .collect(counting());
Enter fullscreen mode Exit fullscreen mode
  • Collectors.summarizingDouble/Long/Int()
DoubleSummaryStatistics  result  = givenList.stream()
.collect(summarizingDouble(String::length));

Enter fullscreen mode Exit fullscreen mode

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()
Optional<String> result = givenList.stream()
.collect(maxBy(Comparator.naturalOrder()));
Enter fullscreen mode Exit fullscreen mode
  • Collectors.groupingBy()
Map<Department, List<Employee>> byDept =
employees.stream()
.collect(Collectors.
groupingBy(Employee::getDepartment));
Enter fullscreen mode Exit fullscreen mode
 Map<Integer, Set<String>> result = givenList.stream()
.collect
(groupingBy(String::length, toSet()));
Enter fullscreen mode Exit fullscreen mode
Map<Department, Integer> totalByDept  = employees.stream()
.collect(Collectors
.groupingBy(Employee::getDepartment
.Collectors.summingInt(Employee::getSalary)));
Enter fullscreen mode Exit fullscreen mode
  • Collectors.partitioningBy()
Map<Boolean, List<String>> result =
givenList.stream()
.collect(partitioningBy(s -> s.length() > 2))
Enter fullscreen mode Exit fullscreen mode

{false=["a", "bb", "dd"], true=["ccc"]}

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

Enter fullscreen mode Exit fullscreen mode
  • Collectors.teeing()
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));
Enter fullscreen mode Exit fullscreen mode

--java 12 sonrası

numbers.stream()
.collect(teeing( minBy(Integer::compareTo),
maxBy(Integer::compareTo),
(min, max) ->
));

Enter fullscreen mode Exit fullscreen mode
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;
  }
 ));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)