使用java 8中的stream读取以空格分隔的文本文件的第一列

时间:2014-11-16 22:25:03

标签: parsing java-8 java-stream

我的尝试:

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);

仍然没有运气。

1 个答案:

答案 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);

    }
}