我上课
class Person {
public List<BaseballPlayer> baseballPlayers;
public List<MmaFighter> mmaFighters;
public List<RugbyPlayer> rugbyPlayers;
}
在每个对象播放器中,其id都有String属性。我正在尝试收集列表中的所有ID
List<String> baseballPlayersIds = person.baseballPlayers.stream()
.map(s -> s.getId()).collect(Collectors.toList());
List<String> mmaFightersIds = person.mmaFighters.stream()
.map(s -> s.getId()).collect(Collectors.toList());
List<String> rugbyPlayersIds = person.rugbyPlayers.stream()
.map(s -> s.getId()).collect(Collectors.toList());
baseballPlayersIds.addAll(mmaFightersIds);
baseballPlayersIds.addAll(rugbyPlayersIds);
现在我正在尝试通过使用Stream.concat()简化事情并改善逻辑。
Stream<List<BaseballPlayer>> baseballPlayersIdsStream = Stream.of(person.baseballPlayers);
Stream<List<MmaFighter>> mmaFightersIdsStream = Stream.of(person.mmaFighters);
Stream<List<RugbyPlayer>> rugbyPlayersIdsStream = Stream.of(person.rugbyPlayers);
Stream<List<? extends Object>> personStream = Stream.concat(baseballPlayersIdsStream, Stream.concat(mmaFightersIdsStream, rugbyPlayersIdsStream));
但是我不知道我是否应该对这3个流中出现的新流类型使用泛型?还尝试为所有3个类创建父类,以在流diamand中代替Object使用。此personStream值得怀疑。
答案 0 :(得分:6)
尝试一下。
<input type="text" />
或
List<String> allIds = Stream.of(
person.baseballPlayers.stream().map(p -> p.getId()),
person.mmaFighters.stream().map(p -> p.getId()),
person.rugbyPlayers.stream().map(p -> p.getId()))
.flatMap(s -> s)
.collect(Collectors.toList());
答案 1 :(得分:2)
如果您在所有类中实现一个通用接口:
interface Team {
String getId();
}
您可以使用以下代码:
List<BaseballPlayer> baseballPlayers = ...;
List<MmaFighter> mmaFighters = ...;
List<RugbyPlayer> rugbyPlayers = ...;
List<String> identfiers = Stream.of(baseballPlayers, mmaFighters, rugbyPlayers)
.flatMap(Collection::stream)
.map(Team::getId)
.collect(Collectors.toList());