Helper189
Helper189

Reputation: 11

How to get the median of a 2d Arraylist

I'm trying to get the median of an ArrayList that has 110 elements. Every 5 elements is a node and I want the median of the nodes. I have tried this code but it's throwing an out of bound error. Any suggestions?

for(int i = 0; i < list.size(); i++)
{
    double Median = 0;
    for(int j = 0; j < list.size(); j++)
    {
        Median = ((list[i-1][j]/2) + (list[i-1][j]/2)-1)/2;
    }
    System.out.println(Median);
}

Thank you!!

Upvotes: 0

Views: 111

Answers (1)

ljleb
ljleb

Reputation: 312

Here's how I would do it:

static List<Double> findMediansOf(List<Double> nodes) {
    List<Double> medians = new ArrayList<>();

    // preventing out of bounds
    if (nodes.isEmpty()) {
        return medians;
    }

    for (int i = 0; i < nodes.size(); i += 5) {
        List<Double> unsortedNode = nodes.subList(i, i + 5);

        // sorting `unsortedNode`
        List<Double> node = unsortedNode.stream()
            .sorted()
            .collect(Collectors.toList());

        // node has always a size of 5, no need to average in case of an even element count
        medians.add(node.get(2));
    }

    return medians;
}

Now if you want to print the result, you just have to do:

findMediansOf(nodes).forEach(System.out::println);

Upvotes: 1

Related Questions