从存储在文件中的行数据中获取不同的值

时间:2017-07-18 09:57:27

标签: java

我有一个.data文件包含这些

这样的表格数据

Id ZIP-code Age Disease

1 12377 39心脏病

2 12302 32心脏病

3 12378 37心脏病

4 45605 53胃炎

5 45609 62心脏病

6 45606 57癌症

7 78905 40心脏病

8 78973 46癌症

9 78907 42癌症

我希望得到Disease属性的唯一/不同值,并将它们存储在数组或列表中。任何人都可以帮忙!

2 个答案:

答案 0 :(得分:0)

伪代码:

1.Class Row (Id ZIP-code Age Disease)
2.HashMap <String,ArrayList<Row>>
3.for each line split by comma
3.a Check if column[5] exists in hashmap
    i) if Yes add Row to corresponding arraylist
    ii)if No  Create new arraylist add Row and then add to the HashMap

答案 1 :(得分:0)

假设您可以读取您的数据,我可能会使用stream api来减少数据集。请参阅下面“功能”中的逻辑。

public class playground {

private static class Row {
    String id;
    String  zip;
    String age;
    String disease;

    public Row(String id, String zip, String age, String disease) {
        this.id = id;
        this.zip = zip;
        this.age = age;
        this.disease = disease;
    }
}


private static Set<String> function(List<Row> rows) {
    return rows.stream().map(row -> {
        return row.disease;
    }).collect(Collectors.toSet());
}

private static List<Row> readDate(String filePath) {

    ArrayList<Row> rows = new ArrayList<Row>();
    try (Stream<String> stream = Files.lines(Paths.get(filePath))) {

        stream.forEach(
                line -> {
                    String[] split = line.split(" ");
                    rows.add(new Row(split[0], split[1], split[2], split[3]));
                }
        );

    } catch (IOException e) {
        e.printStackTrace();
    }
    return rows;
}

public static void main(String[] args) {

    List<Row> rows = readDate("...filepath.data");
    Set<String> unique = function(rows);
    assert(unique.size() == 2);
}

}