如何读取CSV等数据集的纵向列数据并过滤取值唯一的列
实现思路与修改后代码
核心逻辑:要处理列维度的判断,需要先把所有过滤后的有效行暂存,再逐列统计值的唯一性,最后筛选保留列输出。
具体实现步骤
- 新增集合暂存所有无
?的有效行数据,同时确认列总数 - 逐列遍历,用Set去重统计该列的不同值数量,数量>1的列标记为保留列
- 遍历所有有效行(包含表头、类型行),仅输出被标记为保留的列内容
注意:原代码用
split(" ")分割多空格分隔的内容会生成空字符串,统一替换为split("\\s+")适配多空格分隔场景。
完整代码
public void dataProcessing(){ File file = new File("insertFilePathHere"); try { Scanner input = new Scanner(file); // 读取表头、类型行 String titles = input.nextLine(); String[] titleArr = titles.split("\\s+"); String types = input.nextLine(); String[] typeArr = types.split("\\s+"); int columnCount = titleArr.length; // 暂存所有有效行 List<String[]> validRows = new ArrayList<>(); while (input.hasNext()){ String line = input.nextLine(); // 过滤含?的不完整行 if (line.contains("?")){ continue; } String[] row = line.split("\\s+"); validRows.add(row); } // 统计需要保留的列索引 List<Integer> keepColumns = new ArrayList<>(); for (int col = 0; col < columnCount; col++) { Set<String> valueSet = new HashSet<>(); for (String[] row : validRows) { valueSet.add(row[col]); // 只要超过1个不同值就可以提前终止当前列的统计,提升效率 if (valueSet.size() > 1) { break; } } if (valueSet.size() > 1) { keepColumns.add(col); } } // 输出过滤后的表头 for (Integer col : keepColumns) { System.out.printf("%10s", titleArr[col]); } System.out.println(); // 输出过滤后的类型行 for (Integer col : keepColumns) { System.out.printf("%10s", typeArr[col]); } System.out.println(); // 输出过滤后的所有有效行 for (String[] row : validRows) { for (Integer col : keepColumns) { System.out.printf("%10s", row[col]); } System.out.println(); } } catch (FileNotFoundException e) { e.printStackTrace(); } }
内容的提问来源于stack exchange,提问作者joJaInDaHouse
相关产品推荐
相关产品推荐

