使用条件条件对流进行分组,而无需使用forEach和两个外部列表

时间:2018-09-24 15:20:54

标签: java-8 java-stream

我有一个贸易对象,它具有inQty,outQty和tradeType。 TradeType可以是“固定”或“可移动”。数量字段的类型为Double。

使用Java 8流可以将流分为以下两组

1.All Trades that are 'Fixed' + All trades that are 'Moveable' and
have both inQty and outQty greater than 0.0

2. All trades that are 'Moveable' and inQty and outQty are zero value
(0.0)

我知道的一种方法是使用forEach并将对象添加到两个不同的交易数组列表中。 是否有更好的方法来实现这一目标?

List<Trade> storageAndNonZeroMoveableTrades= new ArrayList<>();
List<Trade> zeroMoveableTrades= new ArrayList<>();
trades.forEach( i -> {
            if(i.tradeType().equals(STORAGE_TRADE)){
                storageAndNonZeroMoveableTrades.add(i);
            }else if(i.tradeType().equals(MOVEABLE_TRADE)){
                    if(Double.compare(i.inQty(), 0.0d) != 0 &&
                        Double.compare(i.outQty(), 0.0d) != 0){
                            storageAndNonZeroMoveableTrades.add(i);
                }else{
                        zeroMoveableTrades.add(i);
                    }
            }
        });

1 个答案:

答案 0 :(得分:0)

另一种选择是使用groupingBy收集器。

public class Main {
    public static void main(String... args) {
        Trade t1 = new Trade(0.0, 0.0, FIXED);
        Trade t2 = new Trade(1.1, 2.2, FIXED);
        Trade t3 = new Trade(0.0, 0.0, MOVEABLE);
        Trade t4 = new Trade(3.3, 4.4, MOVEABLE);
        Stream<Trade> trades = Stream.of(t1, t2, t3, t4);

        Map<String, List<Trade>> groups = trades.collect(Collectors.groupingBy(Main::classify));
        System.out.println(groups);
    }

    static String classify(Trade to) {
        return (to.tradeType == MOVEABLE && to.inQty == 0 && to.outQty == 0)
                ? "zeroMoveableTrades" : "storageAndNonZeroMoveableTrades";
    }

    public static class Trade {
        public final double inQty;
        public final double outQty;
        public final TradeType tradeType;

        public Trade(double inQty, double outQty, TradeType tradeType) {
            this.inQty = inQty;
            this.outQty = outQty;
            this.tradeType = tradeType;
        }
        @Override
        public String toString() {
            return "{inQty="+ inQty +", outQty="+ outQty +", tradeType="+ tradeType +"}";
        }
    }

    public enum TradeType {
        FIXED, MOVEABLE
    }
}