Find median from data Stream || Java || Simple solution using heaps ||Easy to understand
\n\npublic class MedianFinder {\n\n    PriorityQueue<Integer> max;     //stores the first half of elements(as present in sorted array)\n    PriorityQueue<Intege
\n```\npublic class MedianFinder {\n\n    PriorityQueue<Integer> max;     //stores the first half of elements(as present in sorted array)\n    PriorityQueue<Integer> min;     //stores the second half of elements\n    public MedianFinder() {\n        max = new PriorityQueue<>(Collections.reverseOrder());       //maxheap to store first half of elements\n        min = new PriorityQueue<>();                                                     //minheap to store second half of elements\n    }\n    \n    public void addNum(int num) {\n        if(max.isEmpty() || num<max.peek()){\n            max.add(num);       //if element lies in first half,i.e,if element is less than top of maxheap or if maxheap is empty, add to maxheap\n        }else{\n            min.add(num);       //else add to min heap\n        }\n        if(max.size()>(min.size()+1)){  //balance both heaps if difference of size greater than 1(max difference will be 2 in any case as it is balanced after adding every element)\n            min.add(max.peek());max.poll();\n        }else if(min.size()>(max.size()+1)){\n            max.add(min.peek());min.poll();\n        }\n    }\n    \n    public double findMedian() {\n        //System.out.println(max.size()+ " "+ min.size());\n        if(max.size()==min.size()) return (double)(max.peek()+min.peek())/2;\n        else if(max.size()>min.size()) return max.peek();\n        else return min.peek();\n    }\n}\n```
[]