How to find Median in a stream of integers (running integers) in Java

In this module, we are going to discuss finding the median in a stream of integers using Java. Let us first see what is a Median and how to calculate the median for given numbers.

Median: To calculate the median first, we have to arrange the given number of integers in increasing or decreasing order if the numbers are of odd length we will return the middle element as a median. If it is even length we would perform an average between two middle elements and return the result as a median.

Test Criteria:

let us consider an array arr={32,22,55,9,35,36} For this stream of Integers
add Integer1 ={32} -> median=32.0
add Integer2={32,22}->median=27.0
add Integer3={32,22,55}->median=32.0
add Integer4={32,22,55,9}->median=27.0  and so on

Java Code to Find Median In Stream of Integers

Here, what we will use is List which will help us to sort the elements in sorting order and then finding the middle elements by finding the size of list.

import java.io.*;
import java.util.*;
public class median
{
    public static int check_median(List<Integer> list1)        //calculation of median
    {
        Collections.sort(list1);
        int size=list1.size();
        int middle=size/2;
        if((size%2)==0)                                       //Length of list is even
        {
            int res=(list1.get(middle-1)+list1.get(middle))/2;
            return res;
        }
        else                                                 //Length of list is odd
        {
            return list1.get(middle);
        }
    }
    public static void result_median(int ar[],int n)           //returning results
    {
        List<Integer> list=new ArrayList<>();
        for(int i=0;i<n;i++)
        {
            list.add(ar[i]);                     //adding array numbers one by one to list
            float med=check_median(list);        //result for median
            System.out.println(med);
        }
    }
    public static void main(String[] args)throws IOException
    {
        int arr[]={32,22,55,9,35,36};               //creating an array stream of integers
        result_median(arr,arr.length);
    }
}

Output:

32.0
27.0
32.0
27.0
32.0
33.0

Explanation :

Here, what we have done is we initially took an array and passed the array to function  result_median() in which we created a list for adding numbers to that list, and this list is passed to the function check_median() which will return median of the list and thus, printing the median.

Also read: Solve Coin Change problem in Java

Leave a Reply

Your email address will not be published. Required fields are marked *