Java 8个流,lambda

h79rfbju  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(152)

我正在努力学习如何在日常编程中利用Java8的特性(比如Lambdas和流),因为它可以使代码更干净。
以下是我目前正在做的工作:我从一个本地文件中获取一个字符串流,其中包含一些数据,稍后我将其转换为对象。输入文件结构如下所示:

Airport name; Country; Continent; some number;

我的代码如下所示:

public class AirportConsumer implements AirportAPI {

List<Airport> airports = new ArrayList<Airport>();

@Override
public Stream<Airport> getAirports() {
    Stream<String> stream = null;
    try {
        stream = Files.lines(Paths.get("resources/planes.txt"));
        stream.forEach(line -> createAirport(line));

    } catch (IOException e) {
        e.printStackTrace();
    }
    return airports.stream();
}

public void createAirport(String line) {
    String airport, country, continent;
    int length;

    airport = line.substring(0, line.indexOf(';')).trim();
    line = line.replace(airport + ";", "");
    country = line.substring(0,line.indexOf(';')).trim();
    line = line.replace(country + ";", "");
    continent = line.substring(0,line.indexOf(';')).trim();
    line = line.replace(continent + ";", "");
    length = Integer.parseInt(line.substring(0,line.indexOf(';')).trim());
    airports.add(new Airport(airport, country, continent, length));
    }
}

在我的主类中,我迭代对象流并打印结果:

public class Main {


public void toString(Airport t){
  System.out.println(t.getName() + " " + t.getContinent());
}

public static void main(String[] args) throws IOException {
    Main m = new Main();
    m.whatever();

}

private void whatever() throws IOException {
    AirportAPI k = new AirportConsumer();
    Stream<Airport> s;
    s = k.getAirports();
    s.forEach(this::toString);

}

}

我的问题是:我怎样才能优化这段代码,这样我就不必单独解析文件中的行,而是直接从源文件创建一个对象流Airport?或者这是我可以做到的程度吗?

abithluo

abithluo1#

您需要使用map()来转换经过的数据。

Files.lines(Paths.get("resources/planes.txt"))
     .map(line -> createAirport(line));

这将返回一个Stream<Airport>-如果你想返回一个List,那么你需要在最后使用collect方法。
这种方法也是无状态的,这意味着您不需要示例级的airports值。
您需要更新createAirport方法以返回以下内容:

public Airport createAirport(String line) {

    String airport = line.substring(0, line.indexOf(';')).trim();
    line = line.replace(airport + ";", "");
    String country = line.substring(0,line.indexOf(';')).trim();
    line = line.replace(country + ";", "");
    String continent = line.substring(0,line.indexOf(';')).trim();
    line = line.replace(continent + ";", "");
    int length = Integer.parseInt(line.substring(0,line.indexOf(';')).trim());
    return new Airport(airport, country, continent, length);
}

如果你正在寻找一种更实用的代码方法,你可能需要考虑重写createAirport,这样它就不会改变行。构建器也适合这种事情。

public Airport createAirport(final String line) {
    final String[] fields = line.split(";");
    return new Airport(fields[0].trim(), 
                       fields[1].trim(), 
                       fields[2].trim(), 
                       Integer.parseInt(fields[3].trim()));
}

把所有这些放在一起,您的类现在看起来像这样。

public class AirportConsumer implements AirportAPI {

    @Override
    public Stream<Airport> getAirports() {
        Stream<String> stream = null;
        try {
            stream = Files.lines(Paths.get("resources/planes.txt"))
                                   .map(line -> createAirport(line));
        } catch (IOException e) {
            stream = Stream.empty();
            e.printStackTrace();
        }
        return stream;
    }

    private Airport createAirport(final String line) {
        final String[] fields = line.split(";");
        return new Airport(fields[0].trim(), 
                           fields[1].trim(), 
                           fields[2].trim(), 
                           Integer.parseInt(fields[3].trim()));
    }
}
yuvru6vn

yuvru6vn2#

Steve发布的代码看起来很棒。但仍有两个地方需要改进:1,如何拆分字符串。2,如果用户忘记或不知道关闭通过调用getAirports()方法创建的流,可能会导致问题。因此,最好就地完成任务(toList()或其他)。以下是abacus-common的代码

try(Reader reader = IOUtil.createBufferedReader(file)) {
    List<Airport> airportList = Stream.of(reader).map(line -> {
        String[] strs = Splitter.with(";").trim(true).splitToArray(line);
        return Airport(strs[0], strs[1], strs[2], Integer.valueOf(strs[3]));
    }).toList();
} catch (IOException e) {
    throw new RuntimeException(e);
}

//或通过Try

List<Airport> airportList = Try.stream(file).call(s -> s.map(line -> {
    String[] strs = Splitter.with(";").trim(true).splitToArray(line);
    return Airport(strs[0], strs[1], strs[2], Integer.valueOf(strs[3]));
}).toList())

披露:我是abacus-common的开发者。

相关问题