如果你坚持使用
streams
然后基本上需要一个映射器函数来映射文件的每一行
imdb。csv
类的实例
InformationTypes
.
在下面的代码中,我使用
record
(而不是类),只是为了让人们意识到自JDK 14以来它在Java中的存在。它简单地避免了编写方法,例如
equals
和
toString
(除其他外)。
还请注意,我使用
method reference
调用
映射器
来自流处理代码的函数。
我还更改了变量的名称,例如
Title
到
title
,以便遵守
Java naming conventions
.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public record InformationTypes(String title,
String year,
List<String> genre,
String runTime,
String rating,
String votes,
String director,
List<String> cast) {
private static InformationTypes mapper(String line) {
String[] parts = line.split(",");
String title = parts[0];
String year = parts[1];
List<String> genre = Arrays.stream(parts[2].split(";"))
.collect(Collectors.toList());
String runTime = parts[3];
String rating = parts[4];
String votes = parts[5];
String director = parts[6];
List<String> cast = Arrays.stream(parts[7].split(";"))
.collect(Collectors.toList());
return new InformationTypes(title, year, genre, runTime, rating, votes, director, cast);
}
public static void main(String[] args) {
Path path = Paths.get("imdb.csv");
try (Stream<String> lines = Files.lines(path)) {
List<InformationTypes> allParts = lines.skip(1L)
.map(InformationTypes::mapper)
.collect(Collectors.toList());
allParts.forEach(System.out::println);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
这是我使用您问题中的示例数据运行上述代码时得到的输出。
InformationTypes[title=In the Heat of the Night, year=1967, genre=[Crime, Drama, Mystery], runTime=110, rating=7.9, votes=68739, director=Norman Jewison, cast=[Sidney Poitier, Rod Steiger, Warren Oates, Lee Grant]]
InformationTypes[title=Forushande, year=2016, genre=[Drama], runTime=124, rating=7.8, votes=52643, director=Asghar Farhadi, cast=[Shahab Hosseini, Taraneh Alidoosti, Babak Karimi, Mina Sadati]]
InformationTypes[title=Rogue One, year=2016, genre=[Action, Adventure, Sci-Fi], runTime=133, rating=7.8, votes=564143, director=Gareth Edwards, cast=[Felicity Jones, Diego Luna, Alan Tudyk, Donnie Yen]]