简体   繁体   中英

Java Stream: Merging multiple results read from separate CSV files?

I am reading City and Country data from 2 CSV files and need to merge the result using Java Stream (I need to keep the same order as the first result). I thought using parallel stream or ComletableFuture, but as I need the result of first fetch for passing as parameter to the second fetch, I am not sure if they are suitable for this scenario.

So, in order to read data from the first query and pass the result of this query to the second one and obtain result, what should I do in Java Stream?

Here are the related entities. I have to relate them using country code values.

Assume that I just need the country names for the following cities. Please keep in mind that, I need to keep the same order as the first result. For example, if the result is [Berlin, Kopenhag, Paris] then the second result should be the same order as [Germany, Denmark, France].

City:


id   | name     | countryCode |
------------------------------
1    | Berlin   | DE          |
2    | Munich   | DE          |
3    | Köln     | DE          |
4    | Paris    | FR          |
5    | Kopenhag | DK          |
...

Country:


id     | name      | code        |
---------------------------------- 
100    | Germany   | DE          |
105    | France    | FR          |
108    | Denmark   | DK          |
...

Here are the related classes:

public class City{

    @CsvBindByPosition(position = 0)
    private Integer id;

    @CsvBindByPosition(position = 1)
    private String name;

    @CsvBindByPosition(position = 2)
    private String countryCode;

    // setters, getters, etc.
}
public class Country {

    @CsvBindByPosition(position = 0)
    private Integer id;

    @CsvBindByPosition(position = 1)
    private String name;

    @CsvBindByPosition(position = 2)
    private String code;

    // setters, getters, etc.
}

You can merge your data with stream, for example add an countryName in City:

    List<Country> countries = // Your CSV Country lines
    List<City> cities = // Your CSV City lines

    cities.forEach(city -> city.setCountryName(countries.stream()
            .filter(country -> country.getCode().equals(city.getCountryCode()))
            .map(Country::getName).findAny().orElse(null)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM