:
static Map<Predicate<Base>,Function<Base,Long>> ACCESSORS;
static {
Map<Predicate<Base>,Function<Base,Long>> m=new HashMap<>();
m.put(Object1.class::isInstance, base -> ((Object1)base).getSerialNr());
m.put(Object2.class::isInstance, base -> ((Object2)base).getPartNr());
ACCESSORS=Collections.unmodifiableMap(m);
}
static Stream<Long> get(Base b) {
return ACCESSORS.entrySet().stream()
.filter(e -> e.getKey().test(b))
.map(e -> e.getValue().apply(b));
}
get
方法は、述語がためにテストケースがある、相互に排他的であることを前提としていこれらの非interface
タイプです。
次に、あなたのようにそれを使用することができます。
List<Long> result = baseList.stream()
.flatMap(YourClass::get)
.collect(Collectors.toList());
ます。またget
メソッドをインライン化できますが、それは読みやすさを改善していない:すべての
List<Long> result = baseList.stream()
.flatMap(b -> ACCESSORS.entrySet().stream()
.filter(e -> e.getKey().test(b))
.map(e -> e.getValue().apply(b)))
.collect(Collectors.toList());
単に 'Base'インタフェースで' long getId() 'を宣言してみませんか? – Holger
残念ながらそれは不可能です。それはインターフェイスでgetId()を持たないのが理にかなっている私の「現実世界の問題」の単純すぎる例です。 – paddy3k