Home > Mobile >  Java filter how to keep null values
Java filter how to keep null values

Time:04-11

Code:

Stream<DbPacket> dbPackets = getDataContext(false, isTrue).getPackets().values()
                .stream();
dbPackets = dbPackets.filter(
                        dbPacket -> "A".equals(dbPacket.getTariff().getCode()));

Not every Packet can have Tariff, for example:

Packet 1 have Tariff, Code A

Packet 2 have Tariff, Code B

Packet 3 don't have Tariff and don't have Code

So in some cases dbPacket.getTariff().getCode() can be null. I need to edit my code, that if Packet don't have Tariff, and dbPacket.getTariff().getCode() is null, then filter will keep this Packet. In this case system have to return Packet 1 (because Code is A) and Packet 3 (because Packet don't have Tariff and Code). How can I modify my code?

CodePudding user response:

I think this is what you're looking for:

List result = dbPackets
   .stream()
   .filter(dbPacket -> dbPacket.getTariff() == null || dbPacket.getTariff().getCode() == null || "A".equals(dbPacket.getTariff().getCode()))
   .collect(Collectors.toList());

CodePudding user response:

What stopping you from doing this?

dbPackets = dbPackets.filter(
                dbPacket -> dbPacket.getTariff() == null || "A".equals(dbPacket.getTariff().getCode() || dbPacket.getTariff().getCode() == null ));
  • Related