I have the below code which does find duplicates in a String without HashMap, HashSet etc. but I want a better solution than this one. Please help I am new to Java programming. I believe Java is powerful enough to give that P.S- Its not that i am trying to avoid HashMap et al in Java Collections. I just want a sleeker solution
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");
}
}
Though Hashmap and Hashset best suit this requirement. But in case you don't want to use it you can also achieve the same thing more efficiently:
You can use Java8 streams to write your entire countWords method in a single line code (follow the inline comments):
static void countWords(String st){
Map<String, Long> wordsAndCounts =
Arrays.stream(st.split("\\s")). //Splt the string by space i.e., word
collect(Collectors.groupingBy( //Apply groupby
Function.identity(), //Map each word
Collectors.counting() //Count how many words
));
System.out.println(wordsAndCounts);
}
OUTPUT:
{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);
}
}
}