Tengo un archivo CSV así:
"user_id","age","liked_ad","location" 2145,34,true,USA 6786,25,true,UK 9025,21,false,USA 1145,40,false,UKEl archivo csv continúa. Me di cuenta de que hay identificadores de usuario duplicados dentro del archivo y, por lo tanto, lo que estoy tratando de hacer es averiguar qué usuarios tienen las respuestas más "verdaderas" para la columna "Me gusta_anuncios". Estoy muy atascado en cómo hacer esto en Java y agradecería cualquier ayuda.
Esto es lo que tengo hasta ahora para analizar literalmente el archivo:
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(); }Estoy atascado sobre adónde ir desde aquí para lograr lo que estoy tratando de lograr.
Puede almacenar la frecuencia del valor true de liked_ad para cada user_id en un Map<String, Integer> map y luego ordenar el Map en valores .
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); } }Dados los siguientes datos en el archivo:
"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,UKla salida será
1145=3 6786=2 2145=2El siguiente código debe hacer lo que desea lograr:
public static void main(String[] args) throws IOException { SortedMap<String, Integer> stats = new TreeMap<>(Collections.reverseOrder()); Files.readAllLines(Paths.get(args[0])).forEach((line) -> { String[] columns = line.split(","); if (Boolean.valueOf(columns[2])) { stats.compute(columns[0], (key, value) -> value == null ? 1 : value + 1); } }); for (Entry<String, Integer> entry : stats.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } }