Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Calculate the Measures of Central Tendency for a Data Set in Java?

Calculate Central Tendency in Java

Condition for Calculating Measures of Central Tendency in Java

  • Description:Calculating the measures of central tendency for a data set involves finding the mean, median, and mode. In Java, you can use basic data structures like arrays and collections to compute these values. The mean is calculated by summing the data points and dividing by the number of elements, while the median is the middle value of a sorted data set, with special handling for even-sized arrays. The mode is computed using a frequency map, which identifies the most frequently occurring values in the dataset. This approach provides an accurate and efficient way to analyze data and is implemented with standard Java libraries.
Sample Source Code
  • # CentralTendency.java
    package JavaSamples2;

    import java.util.*;

    public class CentralTendency {

    public static double calculateMean(int[] data) {
    double sum = 0;
    for (int num : data) {
    sum += num;
    }
    return sum / data.length;
    }

    public static double calculateMedian(int[] data) {
    Arrays.sort(data); // Sort the data in ascending order
    int length = data.length;

    if (length % 2 == 0) {
    return (data[length / 2 - 1] + data[length / 2]) / 2.0;
    } else {
    return data[length / 2];
    }
    }

    public static List calculateMode(int[] data) {
    Map frequencyMap = new HashMap<>();
    List modes = new ArrayList<>();
    int maxCount = 0;

    for (int num : data) {
    frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
    }

    for (int count : frequencyMap.values()) {
    maxCount = Math.max(maxCount, count);
    }

    for (Map.Entry entry : frequencyMap.entrySet()) {
    if (entry.getValue() == maxCount) {
    modes.add(entry.getKey());
    }
    }

    return modes;
    }

    public static void main(String[] args) {
    int[] data = {5, 3, 8, 7, 5, 3, 5, 2, 6, 8, 9, 5};

    double mean = calculateMean(data);
    System.out.println("Mean: " + mean);

    double median = calculateMedian(data);
    System.out.println("Median: " + median);

    List mode = calculateMode(data);
    System.out.println("Mode: " + mode);
    }

    }
Screenshots
  • STEP 1: The Mean, Median, and Mode results are displayed in the output window.
  • The Mean, Median, and Mode results are displayed in the output window.