Je voudrais demander comment puis-je trouver l'élément le plus fréquent dans un tableau de chaînes 2D et également le nombre d'occurrences de cet élément en Java?
Plus précisement:
public static void mostFrequentElement(String[][] data) { // What should I write here? } String[][] data = { {"apple", "orange", "orange"}, {"grape", "orange", "melon"}, }; mostFrequentElement(data); // The function prints "orange 3" in the console // This is because "orange" is the most frequent element in the data array and it showed up 3 times
J'ai essayé d'utiliser HashMap
mais je me suis HashMap
depuis que je suis un débutant en Java. Merci beaucoup!
3 Réponses :
Cela ressemble à un travail pour un HashMap. En parcourant le tableau 2D et en ajoutant des éléments à la carte ou en incrémentant leurs valeurs mappées de 1 s'ils sont déjà dans la carte, nous pouvons suivre le nombre d'occurrences pour chaque élément. Et en créant également une variable max pour contenir le plus grand nombre d'occurrences jusqu'à présent et en la mettant à jour dans la boucle, à la fin de la boucle, elle contiendra l'élément avec le plus grand nombre d'occurrences. Voici mon implémentation, mais n'hésitez pas à consulter la documentation Java pour les hashmaps, car elle est très utile.
public static void mostFrequentElement(String[][] data) { //keeps track of maximum occurences int max = 0; String maxElem = ""; //mapping the strings to the number of occurences HashMap<String, Integer> map = new HashMap<String, Integer>(); //looping through the 2d array for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) { //if current element is already in the map, increment its occurece by 1 if (map.containsKey(data[i][j])) { map.put(data[i][j], map.get(data[i][j])+1); } //if not, add it to the map with 1 occurence else { map.put(data[i][j], 1); } //if the current element's occurences is bigger than max so far, set it to the max if (map.get(data[i][j]) > max) { max = map.get(data[i][j]); maxElem = data[i][j]; } } } //print out the maximum after looping through all the elements System.out.println(maxElem + " " + max); }
Merci pour l'aide! Le code est très simple à comprendre :)
Pas de problème, heureux de vous aider.
Cette solution comporte 3 étapes:
public class Main { public static void main(String[] args) { String[][] data = { {"apple", "orange", "orange"}, {"grape", "orange", "melon"}, }; HashMap<String, Long> finalHashMap = new HashMap<>(); for (String[] row : data) { HashMap<String, Long> oneDimensionResult = Arrays.asList(row).stream() .collect( Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting())); for (String s : oneDimensionResult.keySet()) { if (finalHashMap.containsKey(s)) { Long count = finalHashMap.get(s); finalHashMap.put(s, oneDimensionResult.get(s) + count); } else { finalHashMap.put(s, oneDimensionResult.get(s)); } } } Entry<String, Long> maxEntry = null; for (Entry<String, Long> entry : finalHashMap.entrySet()) { if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0) { maxEntry = entry; } } System.out.println(maxEntry.getKey() + ":" + maxEntry.getValue()); } }
orange=3
Avez-vous déjà fait des efforts pour résoudre ce problème de devoirs?
J'ai essayé d'utiliser un HashMap mais je suis très confus au milieu
Bonne nouvelle: vous avez 2 réponses ci-dessous qui utilisent cette approche.