Can we extract the main object in the threads

I have a class FootballTeamthat contains a class Footballer. Using streams, you can get FootballTeamfrom the list of football teams, if it FootballTeamcontains Footballerwith a specific one id. Is it possible to do this with threads. ie Get both targetFootballerand targetTeam;

FootballTeam targetTeam = null;
Footballer targetFootballer = null;

for(FootballTeam team : list.getFootballTeams()){
    for(Footballer f : team.getFootballers()) {
        if(f.getId() == 1){
           targetFootballer = f;
           break;
        }
    }
    if(targetFootballer != null) {
        targetTeam = team;
    }
}
+4
source share
1 answer

Do not think in terms of loops, but rather what high-level operation you are doing, for example. finding the first item matching the criteria. The biggest obstacle to expressing such an operation is that Java methods cannot return two values. Using Map.Entryas a type of pair containing both results you can use

Map.Entry<FootballTeam,Footballer> target = list.getFootballTeams()
    .stream()
    .flatMap(team -> team.getFootballers()
                     .stream()
                     .filter(f -> f.getId() == 1)
                     .map(f -> new AbstractMap.SimpleImmutableEntry<>(team, f)))
    .findFirst()
    .orElse(null);

, , , , .

list.getFootballTeams()
    .stream()
    .flatMap(team -> team.getFootballers()
                     .stream()
                     .filter(f -> f.getId() == 1)
                     .map(f -> new AbstractMap.SimpleImmutableEntry<>(team, f)))
    .findFirst()
    .ifPresent(e -> {
        FootballTeam targetTeam = e.getKey();
        Footballer targetFootballer = e.getValue();
        // do your action
    });

, , , . .orElse(null) , target null, , null .

+7

Source: https://habr.com/ru/post/1691886/


All Articles