0

The code:

public class main {
public static void countFrequencies(ArrayList<String> list,int n)
{
    int k=0;
    Map<String, Integer> hm = new HashMap<String, Integer>();

    for (String i : list) {
        Integer j = hm.get(i);
        hm.put(i, (j == null) ? 1 : j + 1);
    }

    for (Map.Entry<String, Integer> val : hm.entrySet()) {
        System.out.println("Element " + val.getKey() + " "
                + "occurs"
                + ": " + val.getValue() + " times");
        k++;
        if(k==n)
            break;
    }
}

public static void main(String[] args)  {
    String nr1;
    ArrayList<String> nr = new ArrayList<String>();
    Scanner obj= new Scanner(System.in);
    System.out.println("Input n");
    int n= obj.nextInt();

    System.out.println("Input k ");
    int k= obj.nextInt();
    System.out.println("Input n elemente: ");
    for(int i=1;i<=n;i++)
    {
            nr1=obj.nextLine();
            System.out.println("Element " + (i));
            nr.add(nr1);
    }
    countFrequencies(nr,k);


}

}

If I run the code everything goes ok until I input the last element in the list, if do It appears as null, it simply doesn't let me input it, also when I print the frequencies list I need it to show the top k elements after the number of frequencies, in the descending order.

2 Answers2

0
   public static void countFrequencies(ArrayList<String> list,int n)
{
    int k=0;
    Map<String, Integer> hm = new HashMap<String, Integer>();
    Map<String, Integer> hm2 = new LinkedHashMap<>();

    for (String i : list) {
        Integer j = hm.get(i);
        hm.put(i, (j == null) ? 1 : j + 1);
    }

    hm.entrySet().stream()
            .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
            .forEachOrdered(i -> hm2.put(i.getKey(),i.getValue()));

    for (Map.Entry<String, Integer> val : hm2.entrySet()) {
        System.out.println("Element " + val.getKey() + " "
                + "occurs"
                + ": " + val.getValue() + " times");
        k++;
        if(k==n)
            break;
    }
}
public static void main(String[] args) {
    String nr1;
    ArrayList<String> nr = new ArrayList<String>();
    Scanner obj= new Scanner(System.in);
    System.out.println("Input n");
    int n= obj.nextInt();

    System.out.println("Input k ");
    int k= obj.nextInt();
    System.out.println("Input n elemente: ");
    obj.nextLine(); // Consuming the space
    for(int i=1;i<=n;i++)
    {
        nr1=obj.nextLine();
        System.out.println("Element " + (i));
        nr.add(nr1);
    }
    countFrequencies(nr,k);
}
  1. You are getting last element as null because your code considering the spaces as input. Hence I consumed the extra space.
  2. And to print it in decreasing order you need another LinkedHashMap which actually maintains the insertion order, and I've used stream to sorted the HashMap by values in reverse Order.
0

You have not used n or k in your method, countFrequencies to sort the frequency map on top k frequencies. Also, I recommend you use Integer.parseInt(obj.nextLine()) instead of obj.nextInt() as discussed here. Apart from these, you can leverage the modern API of Map to merge the frequencies and Stream API to perform the required sorting of top k frequencies.

import java.util.ArrayList;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.stream.Collectors;

class Main {
    public static void countFrequencies(ArrayList<String> list, int k) {
        Map<String, Integer> map = new LinkedHashMap<>();

        for (String i : list) {
            map.merge(i, 1, Integer::sum);
        }

        Map<String, Integer> topTen = map.entrySet()
                                        .stream()
                                        .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                                        .limit(k)
                                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));

        // Display
        topTen.forEach((K, V) -> System.out.println(K + " : " + V));
    }

    public static void main(String[] args) {
        ArrayList<String> nr = new ArrayList<String>();
        Scanner obj = new Scanner(System.in);
        System.out.print("How many strings? ");
        int n = Integer.parseInt(obj.nextLine());

        System.out.print("Enter the value of k to sort the frequency map on top k frequencies: ");
        int k = Integer.parseInt(obj.nextLine());

        for (int i = 1; i <= n; i++) {
            System.out.print("Element " + i + ": ");
            nr.add(obj.nextLine());
        }
        countFrequencies(nr, k);
    }
}

A sample run:

How many strings? 10
Enter the value of k to sort the frequency map on top k frequencies: 3
Element 1: Hello
Element 2: Hi
Element 3: Hello
Element 4: Hi
Element 5: Bye
Element 6: Hello
Element 7: Key
Element 8: Value
Element 9: Pair
Element 10: Map
Hello : 3
Hi : 2
Bye : 1
Arvind Kumar Avinash
  • 50,121
  • 5
  • 26
  • 72