简体   繁体   中英

How to compare between an array string element and set string element in java

Here I need to compare the elements present in a Set with the elements in an array.

   `System.out.println("Enter Student's Article");
    sentence=sc.nextLine();
    lowerCase(sentence);
    String [] array=sentence.split("[ ,;:.?!]+");
    System.out.println("Number of words "+array.length);
    Set <String> set=new HashSet<>(Arrays.asList(array));
    //System.out.println(set.size());
    for(String str:set){
        count=0;
        for(int j=0;j<array.length;j++){
            if(str==array[j])
                count++;
                System.out.println(count);
        }
        System.out.println(str+":"+count);
    }
}`

The logic behind my code is: I received an input sentence and I converted it into lowercase. Then I split each word based on some characters as mentioned in the code and store each splitted word to array. Now I convert it into a set. Now I need to count the frequency of each element in the set with repsect to the array.

For example If I give input as "hi hi hi hello" I would get Number of words 4 hi:3 hello:1

So please help me to solve this.

Try the code below and compare the changes with your original code
     Scanner sc=new Scanner(System.in);
     String sentence=sc.nextLine();
     sentence.toLowerCase();
     String [] array=sentence.split("[ ,;:.?!]+");
     System.out.println("Number of words "+array.length);
     Set <String> set=new HashSet<>(Arrays.asList(array));
     //System.out.println(set.size());
     for(String str:set){
         int count=0;
         for(int j=0;j<array.length;j++){
             if(str.equals(array[j]))
                 count++;
                 //System.out.println(count);
         }
         System.out.println(str+":"+count);
     }

Use the below code count the frequency of each element.

    Map<String , Integer> dictionary=new HashMap<String,Integer>();
    String myWords = "soon hi also soon job mother job also soon later";
    myWords = myWords.toLowerCase();
    String[] array=myWords.split("\\s+");
    for(String s:array){
        if(dictionary.containsKey(s))
            dictionary.put(s, dictionary.get(s)+1);
        else
            dictionary.put(s, 1);
    }
    System.out.println("Number of words "+myWords.length());
    for (String key : dictionary.keySet()) {
        System.out.print(key +":"+ dictionary.get(key));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM