Tengo el siguiente código que encuentra duplicados en una Cadena sin HashMap, HashSet, etc. pero quiero una mejor solución que esta. Por favor ayuda, soy nuevo en la programación de Java. Creo que Java es lo suficientemente poderoso como para dar ese PS: no es que esté tratando de evitar HashMap et al en Java Collections. Solo quiero una solución más elegante
public class practice { static void countWords(String st){ //split text to array of words String[] words=st.split("\\s"); //frequency array int[] fr=new int[words.length]; //init frequency array for(int i=0;i<fr.length;i++) fr[i]=0; //count words frequency for(int i=0;i<words.length;i++){ for(int j=0;j<words.length;j++){ if(words[i].equals(words[j])) { fr[i]++; } } } //clean duplicates for(int i=0;i<words.length;i++){ for(int j=0;j<words.length;j++){ if(words[i].equals(words[j])) { if(i!=j) words[i]=""; } } } //show the output int total=0; System.out.println("Duplicate words:"); for(int i=0;i<words.length;i++){ if(words[i]!=""){ System.out.println(words[i]+"="+fr[i]); total+=fr[i]; } } System.out.println("Total words counted: "+total); } public static void main(String[] args) { // TODO Auto-generated method stub countWords("apple banna apple fruit sam fruit apple hello hi hi hello hi"); } }Aunque Hashmap y Hashset se adaptan mejor a este requisito. Pero en caso de que no quiera usarlo, también puede lograr lo mismo de manera más eficiente:
Puede usar secuencias Java8 para escribir todo su método countWords en un código de una sola línea (siga los comentarios en línea):
static void countWords(String st){ Map<String, Long> wordsAndCounts = Arrays.stream(st.split("\\s")). //Splt the string by space ie, word collect(Collectors.groupingBy( //Apply groupby Function.identity(), //Map each word Collectors.counting() //Count how many words )); System.out.println(wordsAndCounts); }PRODUCCIÓN:
{banna=1, hi=3, apple=3, fruit=2, hello=2, sam=1}public static void main(String[] args) { String s = "abcabcc abc abcdeffrgh"; char[] ch = s.toCharArray(); String temp = ""; int j = 0; for (int i = 0; i < s.length(); i++) { int count = 0; char result = 0; for (j = 0; j < s.length(); j++) { if (ch[i] == ch[j]) { result = ch[i]; count = count + 1; } else { result = ch[i]; } } if (!temp.contains(Character.toString(ch[i]))) { temp = temp + ch[i]; System.out.println(result + "--count--" + count); } } }