我正在尝试从文件中提取一个键值对到哈希映射表中,以便更轻松地操作值。
该文件格式如下:
Activity1:3:Activity2:5:Activity3:7:
Activity4:1:
每行最多有3个活动及其对应的编号。
String currentPath;
Path fullPath;
HashMap<String, String> hm = new HashMap<>();
try {
// Obtain current directory path
currentPath = Paths.get("").toAbsolutePath().toString();
// Obtain full path of data.txt
fullPath = Paths.get(currentPath, "data.txt");
// Check if file exists
if (Files.exists(fullPath)) {
// Read line by line in data.txt
Files.lines(fullPath)
.forEach(line -> hm.put(line.split(":")[0], line.split(":")[1]) );
}
else{
System.out.println("data.txt is not found.");
}
} catch (
IOException e) {
e.printStackTrace();
}
然而,只有第一组键值对被插入了HashMap中。我尝试使用。
.map(s -> s.split(":"))
.collect(Collectors.toMap(r -> r[0], r -> r[1] ))
但是由于
split()
输出的类型是一个数组,而toMap
无法接受这种类型,因此它不能正常工作。
编辑:
public static void main(String[] args) {
String currentPath;
Path filePath;
HashMap<String, String> hm = new HashMap<>();
Pattern delimiter = Pattern.compile(":");
try {
// Obtain current directory path
currentPath = Paths.get("").toAbsolutePath().toString();
// Obtain full path of data.txt
filePath = Paths.get(currentPath, "data.txt");
// Check if file exists
if (Files.exists(filePath)) {
// Read line by line in data.txt
hm = Files.lines(filePath)
.map(delimiter::split) // stream of multiple Array<String>
.flatMapToInt(a -> IntStream.range(0, a.length - 1)) // combine multiple Array<String> to a
// single stream, remove last Array<String>
.filter(i -> i % 2 == 0) // obtain only even indices
.mapToObj(i -> new AbstractMap.SimpleEntry<>(a[i], a[i+1])) // a cannot be resolved. Create new Map, key is Array<String>[even], value is Array<String>[odd]
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a,b) -> a)); //
}
else{
System.out.println("data.txt not found.");
}
} catch (
IOException e) {
e.printStackTrace();
}
for (String objectName : hm.keySet()) {
System.out.println(objectName);
System.out.println(hm.get(objectName));
}
}
flatMapToInt
在这里没有用处。请查看给出的答案并相应地更改您的代码。请注意,filter
和mapToObj
操作符位于flatMap
操作符内部。您无法在flatMap
操作符外部访问数组引用a
,这就是为什么编译器会报错的原因。请查看编译器错误,尝试解释并修复它们。此外,在声明映射时,请使用接口类型而不是实现类型,如下所示:Map<String, String> hm = new HashMap<>();
。 - Ravindra Ranwalafilter
和MapToObj
是filter
的一部分。也注意到了Map
声明,这是一个好习惯吗? - TheKraven