[英]Java 8 Stream Multiple Object Creation from an input File
我正在嘗試讀取一個文件來捕獲要使用Java 8流傳遞給對象的參數。
文件格式為:
10 AA
15 BB
20 CC
必須創建相同數量的對象作為行數,對象采用這些參數。
例如,對象a =新對象(10,AA)。
該文件最多總共有3行。
我已經到了讀取文件,檢查它是否以數字開頭,將其拆分為新行並將每行放在String of [List]中。
List<String[]> input = new ArrayList<>();
try {
input = Files.lines(Paths.get("C:\\Users\\ubaid\\IntelliJ Workspace\\Bakery\\input.txt")).
filter(lines->Character.isDigit(lines.trim().charAt(0))).map(x-> x.split("\\r?\\n")).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
for(String a[] : input){
for(String s : a){
System.out.println(s);
}
}
假設你有:
public class Type {
private int number;
private String text;
// constructor and other methods
}
並且文件格式正確:
List<Type> objs = Files.lines(path)
.map(s -> s.split(" "))
.map(arr -> new Type(Integer.parseInt(arr[0]), arr[1]))
.collect(Collectors.toList());
System.out.println(objs);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.