Question

Display all the distinct numbers and their frequencies in the array. Hint: Use a map. STARTER...

Display all the distinct numbers and their frequencies in the array.
Hint: Use a map.

STARTER CODE:

import java.util.HashMap;

public class NumberFrequncies {
   public static void main(String[] args) {
       int[] numbers = {2, 3, 0, 1, -1, 9, 10, 10, 9, 3, 0, 2};
      
       //TODO: ------------
       /* Add code below to store the distinct numbers and their count
       * in a data structure called numberFrequencyMap
       */

      
      
      
       // -------------Your code ends here--------
      
      
       System.out.println("The distinct numbers contained in the array:");
       numberFrequencyMap.forEach(
           (number, count) -> System.out.println(number + " occurs " + count + " time."));
   }
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Answer:

Explanation:

Array is traversed using for loop and containsKey method is used to check if the number is present in map or not.

If present the value of that key is incremented using get function , otherwise the number is added as key and value is set to 1.

Here is the code:

import java.util.HashMap;

public class Main {
public static void main(String[] args) {
int[] numbers = {2, 3, 0, 1, -1, 9, 10, 10, 9, 3, 0, 2};
  
HashMap<Integer, Integer> numberFrequencyMap = new HashMap<>();

for (int i=0; i<numbers.length; i++)
{
if (numberFrequencyMap.containsKey(numbers[i]))
numberFrequencyMap.put(numbers[i], numberFrequencyMap.get(numbers[i]) + 1);
else
numberFrequencyMap.put(numbers[i], 1);
}
  
System.out.println("The distinct numbers contained in the array:");
numberFrequencyMap.forEach(
(number, count) -> System.out.println(number + " occurs " + count + " time."));
}
}

Output:

The distinct numbers contained in the array: O occurs 2 time. -1 occurs i time. 1 occurs i time. 2 occurs 2 time. 3 occurs 2

PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!

Add a comment
Know the answer?
Add Answer to:
Display all the distinct numbers and their frequencies in the array. Hint: Use a map. STARTER...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA HELP: Directions Write a program that will create an array of random numbers and output...

    JAVA HELP: Directions Write a program that will create an array of random numbers and output the values. Then output the values in the array backwards. Here is my code, I am having a problem with the second method. import java.util.Scanner; import java.util.Random; public class ArrayBackwards { public static void main(String[] args) { genrate(); print(); } public static void generate() { Scanner scanner = new Scanner(System.in);    System.out.println("Seed:"); int seed = scanner.nextInt();    System.out.println("Length"); int length = scanner.nextInt(); Random random...

  • JAVA Code: Complete the method, sumOdds(), below. The method takes in an array of integers, numbers,...

    JAVA Code: Complete the method, sumOdds(), below. The method takes in an array of integers, numbers, and returns the sum of all the odd numbers in the array. The method should return 0 if the array contains no odd numbers. For example, if the given array is [12, 10, 5, 8, 13, 9] then the method should return 27 (5+13+9=27). Starter Code: public class Odds { public static int sumOdds(int[] numbers) { //TODO: complete this method    } }

  • Problem: Use the code I have provided to start writing a program that accepts a large...

    Problem: Use the code I have provided to start writing a program that accepts a large file as input (given to you) and takes all of these numbers and enters them into an array. Once all of the numbers are in your array your job is to sort them. You must use either the insertion or selection sort to accomplish this. Input: Each line of input will be one item to be added to your array. Output: Your output will...

  • 2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert a...

    2. Use hashing (solve_with_Hash(int[] array, int k)) Initialize a counter variable to O: Insert all elements of array in a hashtable For every element in array: counter0 a. b. c. .Look for array[i] . Look for array [幻 + k in the hash map, if found then increment counter. -k in the hash map, if found then increment counter. Remove arrayli] from hash table. d. return counter For example: Input : array[] {1, 5, 3, 4, 2), k 3 Output:...

  • I need to write a program in java that reads a text file with a list...

    I need to write a program in java that reads a text file with a list of numbers and sorts them from least to greatest. This is the starter file. import java.util.*; import java.io.*; public class Lab3 { static final int INITIAL_CAPACITY = 5; public static void main( String args[] ) throws Exception { // ALWAYS TEST FOR REQUIRED INPUT FILE NAME ON THE COMMAND LINE if (args.length < 1 ) { System.out.println("\nusage: C:\\> java Lab3 L3input.txt\n"); System.exit(0); } //...

  • Please answer using java. For this lab you will practice accessing variables in an array and...

    Please answer using java. For this lab you will practice accessing variables in an array and determining if the values are odd. You will finish the method makeOddArray. You will store only the odd values in another array and return that array. Hint: you will need to keep track of how many items you have currently put in the new array and increment that value as you add. This will keep track of your index for the new array. Below...

  • The prime factorization of a number is the unique list of prime numbers that, when multiplied,...

    The prime factorization of a number is the unique list of prime numbers that, when multiplied, gives the number. For example, the prime factorization of 60 is 2 ∗ 2 ∗ 3 ∗ 5. In this problem you must write code to recursively find and return the prime factorization of the given number. You must print these in ascending sorted order with spaces in between. For example, if your input is: 120 then you should print the following output: 2...

  • need help editing or rewriting java code, I have this program running that creates random numbers...

    need help editing or rewriting java code, I have this program running that creates random numbers and finds min, max, median ect. from a group of numbers,array. I need to use a data class and a constructor to run the code instead of how I have it written right now. this is an example of what i'm being asked for. This is my code: import java.util.Random; import java.util.Scanner; public class RandomArray { // method to find the minimum number in...

  • Building Each Exercise Driver Download the drivers (ExerciseX.java) and start by reading the code. Notice in...

    Building Each Exercise Driver Download the drivers (ExerciseX.java) and start by reading the code. Notice in Exercise1.java’s main how each method for the problems below have already been invoked for you (Skeleton Level: Strong). As you complete additional exercises, notice the comments in each file. As exercises progress, you’ll be required to uncomment lines in main or even build parts of the main driver yourself. We’ll start with skeleton files that are almost complete, and then look at drivers where...

  • Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all...

    Homework Assignment on Mimir: Read in a file "numbers.txt" into a Java program. Sum up all the even numbers over 50. Print the result to the console using System.out.println(); The file will only have numbers. Code: import java.io.FileNotFoundException; import java.io.FileReader; import java.util.Scanner; /** * * @author David */ public class ReadingFiles {     /**      * @param args the command line arguments      */     public static void main(String[] args) throws FileNotFoundException {         // TODO code application logic here...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT