Get List<String> while concat 3 Streams from lists of different objects

Georgi Michev :

I have a class

class Person {  
    public List<BaseballPlayer> baseballPlayers;    
    public List<MmaFighter> mmaFighters;    
    public List<RugbyPlayer> rugbyPlayers;  
}

In every object player there is String property for his id. I am trying to collect all ids in list which I do

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);

Now I am trying to simplify things and improve logic by using 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)); 

but I cannot figure should I use generics for type of new stream that comes out of the 3 streams? Also tried to create parent class for all 3 classes to use in the stream diamand instead of Object. This personStream is in doubt.

saka1029 :

Try this.

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());

Or

List<String> allIds = Stream.of(
    person.baseballPlayers.stream().map(BaseballPlayer::getId),
    person.mmaFighters.stream().map(MmaFighter::getId),
    person.rugbyPlayers.stream().map(RugbyPlayer::getId))
    .flatMap(Function.identity())
    .collect(Collectors.toList());

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112136&siteId=1