All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.talanlabs.java.lambda.TryCollector Maven / Gradle / Ivy

The newest version!
package com.talanlabs.java.lambda;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * A Collector implementation processing elements as long as results are success
 * @param 
 */
public class TryCollector implements Collector>, Map>>, Try>> {

    @Override
    public Supplier>>> supplier() {
        return () -> {
            HashMap>> map = new HashMap<>();
            map.put(Try.Type.SUCCESS, new LinkedList<>());
            map.put(Try.Type.FAILURE, new LinkedList<>());
            return map;
        };
    }

    @Override
    public BiConsumer>>, Supplier>> accumulator() {
        return (results, supplier) -> {
            if(results.get(Try.Type.FAILURE).isEmpty()) {
                Try result = supplier.get();
                results.get(result.getType()).add(result);
            }
        };
    }

    @Override
    public BinaryOperator>>> combiner() {
        return (left, right) -> {
            if(!left.get(Try.Type.FAILURE).isEmpty()) {
                return left;
            }

            if(!right.get(Try.Type.FAILURE).isEmpty()) {
                return right;
            }

            left.get(Try.Type.SUCCESS).addAll(right.get(Try.Type.SUCCESS));
            return left;
        };
    }

    @Override
    public Function>>, Try>> finisher() {
        return results -> {
            if(results.get(Try.Type.FAILURE).isEmpty()) {
                List collect = results.get(Try.Type.SUCCESS).stream().
                        map(success -> success.asSuccess().getResult()).
                        collect(Collectors.toList());

                return new Success<>(collect);

            } else {
                return (Failure>) results.get(Try.Type.FAILURE).pop();
            }
        };
    }

    @Override
    public Set characteristics() {
        return new HashSet<>(0);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy