Stream Collect

A lot of times, operations need to be performed on the stream of elements and then collected into the collection.

package org.wesome.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.IntStream;

public class Apple1 {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        /*  never do this   */
        IntStream.rangeClosed(1, 10).map(e -> e * e).forEach(list::add);
        list.stream().forEach(System.out::println);

        list.clear();
        System.out.println("-------------");
        /*  never do this   */
        IntStream.rangeClosed(1, 10).parallel().map(e -> e * e).forEach(list::add);
        list.stream().forEach(System.out::println);
    }
}

stream of the integer is squared and then collect into a list, if the stream is sequential then it somewhere will work, but if the parallel stream will have multiple threads depending upon the no of the core of the CPU will process over the list and will return an incorrect result or order.

The correct way to do this is to collect the elements into Collectors.

package org.wesome.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Apple1 {
    public static void main(String[] args) {
        List<Integer> list;
        list = IntStream.rangeClosed(1, 10).map(e -> e * e).boxed().collect(Collectors.toList());
        list.stream().forEach(System.out::println);
        list.clear();

        System.out.println("-------------");

        list = IntStream.rangeClosed(1, 10).parallel().map(e -> e * e).boxed().collect(Collectors.toList());
        list.stream().forEach(System.out::println);
    }
}

The collect method defined in java.util.stream.Collectors class is a terminal operation. it combines all the results of stream processing as reduction, accumulations or summarizing. it collects the result into Collections or other data structures.

package org.wesome.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

class Apple {
    public static void main(String args[]) {
        List<String> apples = Arrays.asList("Macintosh", "Fuji", "Gala", "Jonagold");

        /*  String Stream save in Collection List */
        List<String> appleList = apples.stream().map(String::toUpperCase).collect(Collectors.toList());
        System.out.println("appleList = " + appleList);

        /*  String Stream save in String array */
        String[] appleArr = apples.stream().map(String::toUpperCase).toArray(String[]::new);
        System.out.println("appleArr = " + Arrays.toString(appleArr));

        /*  String Stream save in String separated by comma */
        String joined = appleList.stream().collect(Collectors.joining(", "));
        System.out.println("joined = " + joined);

        /*  String Stream save in String separated by comma, pre and post */
        String joinedPrePost = appleList.stream().collect(Collectors.joining(", ", "#", "@"));
        System.out.println("joinedPrePost = " + joinedPrePost);

        /*  IntStream creates primitive int, boxed() will convert it into Wrapper Integer to save in List */
        List<Integer> collectBox = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toList());
        System.out.println("collectList = " + collectBox);

        /*  IntStream creates primitive int, mapToObj will convert it into Wrapper Integer to save in List */
        List<Integer> collectList = IntStream.rangeClosed(1, 5).mapToObj(value -> value).collect(Collectors.toList());
        System.out.println("collectList = " + collectList);

        /*  IntStream creates primitive int, mapToObj will convert it into Wrapper Integer to save in List */
        collectList = IntStream.rangeClosed(1, 5).mapToObj(Integer::valueOf).collect(Collectors.toList());
        System.out.println("collectList = " + collectList);

        /*  Collect into Set Interface */
        Set<Integer> collectSet = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toSet());

        /*  Collect into Set implementing Class */
        HashSet<Integer> collectHashSet = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toCollection(HashSet::new));
        System.out.println("collectHashSet = " + collectHashSet);

        /*  Collect into List Interface */
        collectList = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toList());
        System.out.println("collectList = " + collectList);

        /*  Collect into List implementing Class */
        List<Integer> collectArrayList = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.toCollection(ArrayList::new));
        System.out.println("collectArrayList = " + collectArrayList);

        /*  total count    */
        Long collectCounting = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.counting());
        System.out.println("collectCounting = " + collectCounting);

        /*  supplier, accumulator, combiner   */
        List<Integer> collectArrayList1 = IntStream.rangeClosed(1, 5).filter(value -> value % 2 == 0).boxed().collect(ArrayList<Integer>::new, List::add, List::addAll);
        System.out.println("collectArrayList1 = " + collectArrayList1);

        /*  Partition based on boolean value    */
        Map<Boolean, List<Integer>> partitioningBy = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.partitioningBy(element -> element % 2 == 0));
        System.out.println("partitioningBy = " + partitioningBy);

        /*  Collect into Summary Statistics */
        IntSummaryStatistics summaryStatistics = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.summarizingInt(Integer::intValue));
        System.out.println("summaryStatistics sum = " + summaryStatistics.getSum());
        System.out.println("summaryStatistics = max " + summaryStatistics.getMax());
        System.out.println("summaryStatistics = average " + summaryStatistics.getAverage());
        System.out.println("summaryStatistics count = " + summaryStatistics.getCount());

        /*  Collect into sum of stream elements */
        int sum = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.summingInt(Integer::intValue));
        System.out.println("sum = " + sum);

        /*  Collect into average double */
        Double average = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.averagingInt(Integer::intValue));
        System.out.println("average = " + average);

        /*  find max */
        Optional<Integer> max = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.maxBy(Comparator.comparing(Integer::intValue)));
        System.out.println("max = " + max.get());
        max = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.maxBy(Integer::compareTo));
        System.out.println("max = " + max.get());
        max = IntStream.rangeClosed(1, 5).boxed().max(Comparator.comparing(Integer::intValue));
        System.out.println("max = " + max.get());

        /*  find min */
        Optional<Integer> min = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.minBy(Comparator.comparing(Integer::intValue)));
        System.out.println("min = " + min);
        min = IntStream.rangeClosed(1, 5).boxed().collect(Collectors.minBy(Integer::compareTo));
        System.out.println("min = " + min);
        min = IntStream.rangeClosed(1, 5).boxed().min(Comparator.comparing(Integer::intValue));
        System.out.println("min = " + min);

        /*  Collect into Map Interface */
        Map<Integer, List<Integer>> groupingBy = IntStream.concat(IntStream.rangeClosed(1, 5), IntStream.rangeClosed(1, 5)).boxed().collect(Collectors.groupingBy(Integer::intValue, Collectors.toList()));
        System.out.println("groupingBy = " + groupingBy);
    }
}

Stream Collect on User Defined Object

package org.wesome.java8;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
class Fruit {
    int fruitId;
    String fruitName;
    String taste;
    double price;
}

class Apple {
    public static void main(String args[]) {
        List<Fruit> fruits = Arrays.asList(new Fruit(1, "Macintosh", "sweet", 1.1), new Fruit(2, "Fuji", "sweet", 2.2), new Fruit(3, "Gala", "sour", 1.1), new Fruit(4, "Jonagold", "sour", 2.2));

        /*  Convert object into stream strings and concatenate them, separated by commas    */
        String joined = fruits.stream().map(Fruit::getFruitName).collect(Collectors.joining(" -> "));
        System.out.println("joined = " + joined);

        /*  collect fruit name in List  */
        List<String> fruitNameList = fruits.stream().map(Fruit::getFruitName).collect(Collectors.toList());
        System.out.println("fruitNameList = " + fruitNameList);

        /*  collect fruit name in Tree Set  */
        TreeSet<String> fruitNameTreeSet = fruits.stream().map(Fruit::getFruitName).collect(Collectors.toCollection(TreeSet::new));
        System.out.println("fruitNameTreeSet = " + fruitNameTreeSet);

        /*  count total fruit price  */
        Double priceTotal = fruits.stream().collect(Collectors.summingDouble(Fruit::getPrice));
        System.out.println("priceTotal = " + priceTotal);

        /*  collect fruit in map, taste as key and sum of price of fruit as value  */
        Map<String, Double> fruitGroupByTasteAndSum = fruits.stream().collect(Collectors.groupingBy(Fruit::getTaste, Collectors.summingDouble(Fruit::getPrice)));
        System.out.println("fruitGroupByTasteAndSum = " + fruitGroupByTasteAndSum);

        /*  get summery of fruit Id  */
        IntSummaryStatistics intSummaryStatistics = fruits.stream().collect(Collectors.summarizingInt(Fruit::getFruitId));
        System.out.println("intSummaryStatistics = " + intSummaryStatistics);

        /*  collect fruit in map, taste as key and List of Fruits as value  */
        Map<String, List<Fruit>> fruitGroupByTaste = fruits.stream().collect(Collectors.groupingBy(Fruit::getTaste));
        System.out.println("fruitGroupByTaste = " + fruitGroupByTaste);

        /*  collect fruit in map, taste as key and sum of fruit id as value  */
        Map<String, Integer> fruitSummingInt = fruits.stream().collect(Collectors.groupingBy(Fruit::getTaste, Collectors.summingInt(Fruit::getFruitId)));
        System.out.println("fruitSummingInt = " + fruitSummingInt);

        /*  collect fruit in map, fruit id as key and fruit name as value  */
        Map<Integer, String> fruitToMap = fruits.stream().collect(Collectors.toMap(Fruit::getFruitId, Fruit::getFruitName));
        System.out.println("fruitToMap = " + fruitToMap);

        /*  collect fruit in map, fruit Id as key and fruit as value  */
        Map<Integer, Fruit> collect = fruits.stream().collect(Collectors.toMap(fruit -> fruit.getFruitId(), fruit -> fruit));
        System.out.println("collect = " + collect);
    }
}

 

follow us on