我的尝试:
public class TestStream {
public static void main(String[] args) throws Exception {
String[] uniqueWords = Files.lines(Paths.get("/tmp/testfile"), Charset.defaultCharset()).flatMap(line -> Arrays.stream(line.split(" ")).limit(1));
System.out.println(uniqueWords);
}
}
显然File.lines...
部分不返回String数组。我怎样才能做到这一点?
另一次尝试:
List<String> uniqueWords = Files.lines(Paths.get("/tmp/testfile"), Charset.defaultCharset()).flatMap(line -> Arrays.asList(line.split(" ")).stream().findFirst()).collect(Collectors.toList());
System.out.println(uniqueWords);
仍然没有运气。
答案 0 :(得分:3)
终于明白了:
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
/**
* Created by IDEA on 16/11/14.
*/
public class TestDosage {
private final static Pattern pattern = Pattern.compile("\\s+");
public static void main(String[] args) throws Exception {
List<String> x = Files.lines(Paths.get("/tmp/testfile"), Charset.defaultCharset())
.map(line -> pattern.split(line, 2)[0])
.collect(Collectors.toList());
System.out.println(x);
}
}