亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 Java 流從列表中的列表中平均特定值

使用 Java 流從列表中的列表中平均特定值

交互式愛情 2023-06-14 14:25:45
無法弄清楚如何在特定建筑物的列表中讀出動物的平均重量。我寫了另一種方法來獲取每種動物的動物名稱,所以我知道我的堅持是有效的。出色地:public class Zoo {    private List<Animal> animals;    private List<Building> buildings;    public Zoo() {        this.animals = new PersistencyController().giveAnimals();        this.gebouwen = new PersistencyController().giveBuildings();    } public List<Animal> giveAnimalsByKind(String kindName) {        return animals.stream().filter(animal -> animal.getKind().getName() == kindName).sorted(Comparator.comparing(Animal::getWeight)).collect(Collectors.toList());    }    public double giveAvgWeightForAnimalsInBuilding(String buildingName) {        return animals.stream().collect(Collectors.averagingDouble(Animal::getWeight));    }}動物:public class Animal implements Serializable {    private int nr;    private String name;    private double weight;    private Kind kind;    public Animal(int nr, String name, double weight, Kind kind) {        this.nr = nr;        this.name = name;        this.weight= weight;        this.kind= kind;    }    public double getWeight() {        return weight;    }    public void setWeight(double weight) {        this.weight = weight;    }}建筑:public class Building{    private String naam;    private int capaciteit;    private final List<Animal> animals = new ArrayList<>();    public Building(String naam, int capaciteit) {        this.naam = naam;        this.capaciteit = capaciteit;    }}我想獲得每個建筑物的動物的平均重量,所以我的想法是傳遞建筑物的名稱。每個 Building 對象都存儲一個動物列表,我需要 building 對象,因為它存儲了建筑物的名稱,但我不知道如何使用流訪問它。我知道在我發布的代碼中,我實際上還沒有使用 buildingName,但那是因為我什至無法正常獲得動物的平均體重。weight 在 Animal 中存儲為 double 并且我的堅持正在發揮作用,因為我已經以其他方式對此進行了測試。任何對流有經驗的人都將不勝感激,解釋如何通過構建進行過濾并得到這個平均權重。
查看完整描述

1 回答

?
至尊寶的傳說

TA貢獻1789條經驗 獲得超10個贊

如果你有使用 Java9 的自由,我建議你使用flatMapping收集器來完成這件事。這是它的樣子。


Map<String, Double> avgWeightByBuildingName = buildings.stream()

    .collect(Collectors.groupingBy(Building::getName,

        Collectors.flatMapping(b -> b.getAnimals().stream(), 

            Collectors.averagingDouble(Animal::getWeight))));

然而,這里的 java8 解決方案與前者相比看起來有點冗長。


Map<String, Double> avgWeightByBuildingName = buildings.stream()

    .flatMap(b -> b.getAnimals().stream()

        .map(a -> new AbstractMap.SimpleEntry<>(b.getName(), a.getWeight())))

    .collect(Collectors.groupingBy(Map.Entry::getKey, 

        Collectors.averagingDouble(Map.Entry::getValue)));

flatMapping或者考慮按照此答案編寫您自己的收集器。這是我在查看上述答案和 JDK 9 源代碼后想出的一個這樣的實現。


static <T, U, A, R> Collector<T, ?, R> flatMapping(Function<? super T,

            ? extends Stream<? extends U>> mapper, Collector<? super U, A, R> downstream) {

    BiConsumer<A, ? super U> downstreamAccumulator = downstream.accumulator();

    return Collector.of(downstream.supplier(), (r, t) -> {

        try (Stream<? extends U> result = mapper.apply(t)) {

            result.sequential().forEach(u -> downstreamAccumulator.accept(r, u));

        }

    }, downstream.combiner(), downstream.finisher(), 

            downstream.characteristics().toArray(new Characteristics[0]));

}

此外,如以下評論所述,這對于較新的 Java 版本有一個直接的遷移策略。


查看完整回答
反對 回復 2023-06-14
  • 1 回答
  • 0 關注
  • 129 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號