我正在计算文本文件中所有日期的频率。日期存储在解析的.get(0(中,但当我打印频率时,我会得到以下输出:
1946-01-12: 1
1946-01-12: 1
1946-01-12: 1
1946-01-13: 1
1946-01-13: 1
1946-01-13: 1
1946-01-14: 1
1946-01-14: 1
1946-01-14: 1
1946-01-15: 1
而不是
1946-01-12: 3
1946-01-13: 3
1946-01-14: 3
1946-01-15: 1
我想这是因为我必须存储这样的日期("1946-01-12","1946-01-1 2","1946-01-11","1946-191-13","946-01-13"…(。如果我只是打印解析的。get(0(我得到
1946-01-12
1946-01-12
1946-01-12
1946-01-13
1946-01-13
1946-01-13
1946-01-14
1946-01-14
1946-01-14
1946-01-15`
我如何根据下面的代码来解决它?
private static List<WeatherDataHandler> weatherData = new ArrayList<>();
public void loadData(String filePath) throws IOException {
//Read all data
List<String> fileData = Files.readAllLines(Paths.get("filePath"));
System.out.println(fileData);
for(String str : fileData) {
List<String> parsed = parseData(str);
LocalDate dateTime = LocalDate.parse(parsed.get(0));
WeatherDataHandler weather = new WeatherDataHandler(dateTime, Time, temperature, tag);
weatherData.add(weather);
List<String> list = Arrays.asList(parsed.get(0));
Map<String, Long> frequencyMap =
list.stream().collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()));
for (Map.Entry<String, Long> entry : frequencyMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
问题
for循环中的所有内容都在每次迭代中执行。因此,您正在重新创建日期集合,并重新创建流以进行一次又一次的分析。不好。
解决方案
将流和分析代码移动到for循环之外。
将代码重新思考为两个阶段。
- 第一阶段是解析输入,将传入数据预处理为您想要使用的表单。在这种情况下,我们需要读取一个文本文件,将行解析为
LocalDate
对象,并将这些对象添加到集合中。此代码使用for循环 - 第二阶段是流式工作,处理经过改造的数据,收集
LocalDate
对象。此代码位于for循环的之后
在我自己的工作中,我会把这些要点作为注释放在代码中。我会添加分隔线(带有一堆注释或常用符号的注释线(来标记代码中的每个阶段。我可能会把每个阶段都作为一个子程序移动到一个方法中。
顺便说一句,一旦你让他工作了,为了好玩,你可能想尝试用流代替for循环读取文件。Java可以将文件读取为行流。
根据我认为这是如何工作的,我将按如下方式进行。包含注释以解释其他逻辑。主要的想法是在你的主循环中尽可能多地做。使用stream
在循环外创建frequenceyMap
是额外且不必要的工作。
private static List<WeatherDataHandler> weatherData =
new ArrayList<>();
public void loadData(String filePath) throws IOException {
// Read all data
List<String> fileData =
Files.readAllLines(Paths.get("filePath"));
System.out.println(fileData);
// Pre-instantiate the freqency map.
Map<String, Long> frequencyMap = new LinkedHashMap<>();
for (String str : fileData) {
List<String> parsed = parseData(str);
LocalDate dateTime =
LocalDate.parse(parsed.get(0));
WeatherDataHandler weather = new WeatherDataHandler(
dateTime, Time, temperature, tag);
weatherData.add(weather);
// Ensure dateTime is a string. This may not have the desired
// format for date but that can be corrected by you
String strDate = dateTime.toString();
// Use the compute method of Map. If the count is null,
// initialize it to 1, otherwise, add 1 to the existing value.
frequencyMap.compute(strDate,
(date, count) -> count == null ? 1 : count + 1);
}
for (Map.Entry<String, Long> entry : frequencyMap
.entrySet()) {
System.out.println(
entry.getKey() + ": " + entry.getValue());
}
}
您也可以按如下方式打印地图:
frequencyMap.forEach((k,v)->System.out.println(k + ": " + v));
最后,上面的内容可以简化一些地方,比如使用Files.lines(path)
创建流。但是,由于您也在将其写入WeatherDataHandler
列表,并且希望保留您的结构,所以我没有使用该功能。
我简要测试了这个,你可以检查的结果
{1946-01-14=3, 1946-01-15=1, 1946-01-12=3, 1946-01-13=3}
原始文件是
1946-01-12: 1
1946-01-12: 1
1946-01-12: 1
1946-01-13: 1
1946-01-13: 1
1946-01-13: 1
1946-01-14: 1
1946-01-14: 1
1946-01-14: 1
1946-01-15: 1
根据您的喜好修改
代码:
try {
String content = new Scanner(new File("src/main/resources/test.txt")).useDelimiter("\Z").next();
String[] dates= content.split("\n");
Map<String,Long> m
=
Arrays.stream(dates).
map(o->
{return o.split(":")[0];}) //not necessary if you dont have 1s in the text file
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(m.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
这样,您就可以获得列表中具有相同值的元素的数量。
int numerOfElements = Collections.frequency(list, "1946-01-12");