Example usage for java.util.stream Collectors summingDouble

List of usage examples for java.util.stream Collectors summingDouble

Introduction

In this page you can find the example usage for java.util.stream Collectors summingDouble.

Prototype

public static <T> Collector<T, ?, Double> summingDouble(ToDoubleFunction<? super T> mapper) 

Source Link

Document

Returns a Collector that produces the sum of a double-valued function applied to the input elements.

Usage

From source file:Main.java

public static void main(String[] args) {
    Stream<String> s = Stream.of("1", "2", "3");

    double o = s.collect(Collectors.summingDouble(n -> Double.parseDouble(n)));

    System.out.println(o);//from  www  .  j  av  a2s .  co  m
}

From source file:com.grepcurl.random.WeightedCallableChooser.java

public T doRandomOperation() throws Exception {
    if (!_probabilitiesVerified.get()) {
        synchronized (LOCK) {
            if (!_probabilitiesVerified.get()) {
                Validate.isTrue(/*from w ww  .ja v  a  2  s.co m*/
                        this.stream().collect(Collectors.summingDouble(value -> value.probability)) == 1.0);
                _probabilitiesVerified.set(true);
            }
        }
    }
    double p = _objectGenerator.randomProbability();
    double sum = 0;
    for (WeightedCallable<T> c : this) {
        if (p > sum && p <= sum + c.probability) {
            return c.callable.call();
        }
        sum += c.probability;
    }
    throw new IllegalStateException();
}

From source file:com.grepcurl.random.WeightedFunctionChooser.java

public R doRandomFunction(T t) throws Exception {
    if (!_probabilitiesVerified.get()) {
        synchronized (LOCK) {
            if (!_probabilitiesVerified.get()) {
                Validate.isTrue(//from  ww  w  .j  av  a 2  s .c om
                        this.stream().collect(Collectors.summingDouble(value -> value.probability)) == 1.0);
                _probabilitiesVerified.set(true);
            }
        }
    }
    double p = _objectGenerator.randomProbability();
    double sum = 0;
    for (WeightedFunction<T, R> pFun : this) {
        if (p > sum && p <= sum + pFun.probability) {
            return pFun.function.apply(t);
        }
        sum += pFun.probability;
    }
    throw new IllegalStateException();
}

From source file:com.leonarduk.finance.chart.PieChartFactory.java

@SuppressWarnings("unchecked")
public Double getTotal() {
    return (Double) this.dataset.getKeys().stream().collect(Collectors.summingDouble(key -> {
        return (Double) this.dataset.getValue((String) key);
    }));/*from  w ww .  j  a  v  a  2 s .  c o  m*/
}

From source file:de.blizzy.rust.lootconfig.LootConfigDump.java

private float sum(Multiset<Float> chances) {
    return (float) (double) chances.stream().collect(Collectors.summingDouble(f -> f));
}

From source file:no.imr.stox.functions.acoustic.PgNapesIO.java

public static void export2(String cruise, String country, String callSignal, String path, String fileName,
        List<DistanceBO> distances, Double groupThickness, Integer freqFilter, String specFilter,
        boolean withZeros) {
    Set<Integer> freqs = distances.stream().flatMap(dist -> dist.getFrequencies().stream())
            .map(FrequencyBO::getFreq).collect(Collectors.toSet());
    if (freqFilter == null && freqs.size() == 1) {
        freqFilter = freqs.iterator().next();
    }// ww  w  .j a v  a 2 s.c  o m

    if (freqFilter == null) {
        System.out.println("Multiple frequencies, specify frequency filter as parameter");
        return;
    }
    Integer freqFilterF = freqFilter; // ef.final
    List<String> acList = distances.parallelStream().flatMap(dist -> dist.getFrequencies().stream())
            .filter(fr -> freqFilterF.equals(fr.getFreq())).map(f -> {
                DistanceBO d = f.getDistanceBO();
                LocalDateTime sdt = LocalDateTime.ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                Double intDist = d.getIntegrator_dist();
                String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                String hour = StringUtils.leftPad(sdt.getHour() + "", 2, "0");
                String minute = StringUtils.leftPad(sdt.getMinute() + "", 2, "0");
                String log = Conversion.formatDoubletoDecimalString(d.getLog_start(), "0.0");
                String acLat = Conversion.formatDoubletoDecimalString(d.getLat_start(), "0.000");
                String acLon = Conversion.formatDoubletoDecimalString(d.getLon_start(), "0.000");
                return Stream
                        .of(d.getNation(), d.getPlatform(), d.getCruise(), log, sdt.getYear(), month, day, hour,
                                minute, acLat, acLon, intDist, f.getFreq(), f.getThreshold())
                        .map(o -> o == null ? "" : o.toString()).collect(Collectors.joining("\t")) + "\t";
            }).collect(Collectors.toList());
    String fil1 = path + "/" + fileName + ".txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Hour", "Min",
            "AcLat", "AcLon", "Logint", "Frequency", "Sv_threshold").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil1), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
    acList.clear();
    // Acoustic values
    distances.stream().filter(d -> d.getPel_ch_thickness() != null)
            .flatMap(dist -> dist.getFrequencies().stream()).filter(fr -> freqFilterF.equals(fr.getFreq()))
            .forEachOrdered(f -> {
                try {
                    Double groupThicknessF = Math.max(f.getDistanceBO().getPel_ch_thickness(), groupThickness);
                    Map<String, Map<Integer, Double>> pivot = f.getSa().stream()
                            .filter(s -> s.getCh_type().equals("P")).map(s -> new SAGroup(s, groupThicknessF))
                            .filter(s -> s.getSpecies() != null
                                    && (specFilter == null || specFilter.equals(s.getSpecies())))
                            // create pivot table: species (dim1) -> depth interval index (dim2) -> sum sa (group aggregator)
                            .collect(Collectors.groupingBy(SAGroup::getSpecies, Collectors.groupingBy(
                                    SAGroup::getDepthGroupIdx, Collectors.summingDouble(SAGroup::sa))));
                    if (pivot.isEmpty() && specFilter != null && withZeros) {
                        pivot.put(specFilter, new HashMap<>());
                    }
                    Integer maxGroupIdx = pivot.entrySet().stream().flatMap(e -> e.getValue().keySet().stream())
                            .max(Integer::compare).orElse(null);
                    if (maxGroupIdx == null) {
                        return;
                    }
                    acList.addAll(pivot.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey))
                            .flatMap(e -> {
                                return IntStream.range(0, maxGroupIdx + 1).boxed().map(groupIdx -> {
                                    Double chUpDepth = groupIdx * groupThicknessF;
                                    Double chLowDepth = (groupIdx + 1) * groupThicknessF;
                                    Double sa = e.getValue().get(groupIdx);
                                    if (sa == null) {
                                        sa = 0d;
                                    }
                                    String res = null;
                                    if (withZeros || sa > 0d) {
                                        DistanceBO d = f.getDistanceBO();
                                        String log = Conversion.formatDoubletoDecimalString(d.getLog_start(),
                                                "0.0");
                                        LocalDateTime sdt = LocalDateTime
                                                .ofInstant(d.getStart_time().toInstant(), ZoneOffset.UTC);
                                        String month = StringUtils.leftPad(sdt.getMonthValue() + "", 2, "0");
                                        String day = StringUtils.leftPad(sdt.getDayOfMonth() + "", 2, "0");
                                        //String sas = String.format(Locale.UK, "%11.5f", sa);
                                        res = Stream
                                                .of(d.getNation(), d.getPlatform(), d.getCruise(), log,
                                                        sdt.getYear(), month, day, e.getKey(), chUpDepth,
                                                        chLowDepth, sa)
                                                .map(o -> o == null ? "" : o.toString())
                                                .collect(Collectors.joining("\t"));
                                    }
                                    return res;
                                }).filter(s -> s != null);
                            }).collect(Collectors.toList()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

    String fil2 = path + "/" + fileName + "Values.txt";
    acList.add(0, Stream.of("Country", "Vessel", "Cruise", "Log", "Year", "Month", "Day", "Species",
            "ChUppDepth", "ChLowDepth", "SA").collect(Collectors.joining("\t")));
    try {
        Files.write(Paths.get(fil2), acList, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    } catch (IOException ex) {
        Logger.getLogger(PgNapesIO.class.getName()).log(Level.SEVERE, null, ex);
    }
}