对于其他人仍然偶然发现这一点。
使用Stream
API (Java 8),可以这样做
由此可见
- 过滤方法来过滤列表中的第一个标题元素
- map 方法将流中的每个元素映射到新流的另一个元素。
package com.bhavya.stackoverflow.examples.q19575308;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.function.Predicate;
/**
* Java 8 Stream API to handle file reading.
*
* @author bhavya.work
*/
public class StreamTests {
public static void main(String[] args) {
try {
InputStream fileInputStream;
BufferedReader bufferedReader;
final String filepathInSamePackage = "textfile.txt";
//filter predicate
Predicate<String> filterFirstLine =
line -> !(
"Name".equals(line.split("\t", -1)[0])
&& "Hobby".equals(line.split("\t", -1)[1])
);
//Implementation 1 returns Arrays as asked.
System.out.println("==ArrayList==");
fileInputStream = StreamTests.class.getResourceAsStream(filepathInSamePackage);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
bufferedReader
.lines()
.filter(filterFirstLine)
.map(s -> {
String[] splitStrings = s.split("\t", -1);
return Arrays.asList(splitStrings);
}).forEach(System.out::println);
//Implementation 2 returns HashMap as another example
fileInputStream = StreamTests.class.getResourceAsStream(filepathInSamePackage);
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
System.out.println("\n==HashMap==");
bufferedReader
.lines()
.filter(filterFirstLine)
.map(s -> {
String[] splitStrings = s.split("\t", -1);
HashMap<String, String> stringStringMap = new HashMap<>();
stringStringMap.put(splitStrings[0], splitStrings[1]);
return stringStringMap;
}).forEach(System.out::println);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
和输出
==ArrayList==
[Susy, eat fish]
[Anna, gardening]
[Billy, bowling with friends]
==HashMap==
{Susy=eat fish}
{Anna=gardening}
{Billy=bowling with friends}