我有一个像这样的 CSV 文件 -
"user_id","age","liked_ad","location"
2145,34,true,USA
6786,25,true,UK
9025,21,false,USA
1145,40,false,UK
csv 文件继续。我发现文件中有重复的 user_id,所以我想做的是找出哪些用户对“liked_ads”列有最“真实”的答案。 我对如何在 Java 中执行此操作非常困惑,希望得到任何帮助。
这就是我到目前为止所掌握的字面上解析文件的内容 -
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("src/main/resources/advert-data.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext()) {
System.out.print(scanner.next() + " | ");
}
scanner.close();
}
为了实现我想要实现的目标,我陷入了困境。
最佳答案
您可以存储true
的频率liked_ad
的值对于每个 user_id
在 Map<String, Integer> map
然后sort the Map
on values .
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("file.txt"));
// Ignore the header line
if (scanner.hasNextLine()) {
scanner.nextLine();
}
// Store the frequency of liked_ad for each user_id
Map<String, Integer> map = new HashMap<>();
while (scanner.hasNextLine()) {
String[] data = scanner.nextLine().split(",");
if (data.length >= 3 && Boolean.parseBoolean(data[2])) {
map.merge(data[0], 1, Integer::sum);
}
}
// Sort the Map on values and display each entry
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByValue()))
.forEach(System.out::println);
}
}
鉴于文件中的以下数据:
"user_id","age","liked_ad","location"
1145,40,true,UK
2145,34,true,USA
6786,25,true,UK
6786,25,true,UK
1145,40,true,UK
2145,34,true,USA
9025,21,false,USA
1145,40,false,UK
1145,40,true,UK
输出将是
1145=3
6786=2
2145=2
关于java - 对 CSV 文件中的重复项进行分组并根据某些值对数据进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65062471/