Search code examples
javaloopssortinghashmapbubble-sort

Trying to make an array of hashmap keys from an array of hashmap values returning null


I have created a method which takes in a hashmap as input, converts the values into an array, sorts the array using bubble sort and then I want it to use the sorted values to select the first N index keys from the initial hashmap. I understand this is not the best way to do this but that is fine (I have written this method as an alternative).

The method returns null since maxItems is empty and the "System.out.println(entry.getKey());" doesn't print anything to the console.

Thanks for any help!

public String[] getMaxListAlt(int n, HashMap<String, Integer> itemCount) {

    itemCount.values().toArray();

    Integer[] maxArray = itemCount.values().toArray(new Integer[0]);

    int length = maxArray.length;
    for (int i = 0; i < length-1; i++)
        for (int j = 0; j < length-i-1; j++)
            if (maxArray[j] > maxArray[j+1])
            {
                int temp = maxArray[j];
                maxArray[j] = maxArray[j+1];
                maxArray[j+1] = temp;
                
            }

    String[] maxItems = new String[n];
    int maxIndex = n-1;
    System.out.println(maxIndex);


    for (int i=0; i >= n-1; i++) {
        for (Map.Entry<String, Integer> entry : itemCount.entrySet()) {
            if (entry.getValue().equals(maxArray[i])) {
                System.out.println(entry.getKey());
                maxItems[i] = entry.getKey();
            }
        }
    }

        for (int counts : maxArray) {

        System.out.println(counts);

    }

    return maxItems;
}

Solution

  • Your for-loop doesn't run because you've got a typo - int i=0; i>= n-1; but your i can never be larger than your n-1. Instead:

    for (int i=0; i <= n-1; i++) {
        for (Map.Entry<String, Integer> entry : itemCount.entrySet()) {