user3871
user3871

Reputation: 12664

Java alternatives to PHP indexed arrays

I'm trying to iterate over an associative array and tally up how many instances of each combination there are (for use in determining conditional probability of A given B)

For example, in PHP I can iterate over the indexed array $Data[i] given input (A, ~B) and get a result of 2.

$Data[0] = array("A", "~B");
$Data[1] = array("~A", "B");
$Data[2] = array("A", "~B");
$Data[3] = array("A", "B");

I tried replicating this in Java with maps, but maps only allow a unique key for each value... So the following wouldn't work because key A is being used for three entries.

map.put("A", "~B");
map.put("~A", "B");
map.put("A", "~B");
map.put("A", "B");

Is there something else I can use?

Thanks!

Upvotes: 0

Views: 93

Answers (2)

Trevor Freeman
Trevor Freeman

Reputation: 7242

If iteration of the structure is your primary goal, a List<ConditionResult> would seem to be the most appropriate choice for your situation, where ConditionResult is given below.

If maintaining a count of the combinations is the sole goal, then a Map<ConditionResult,Integer> would also work well.

public class ConditionResult
{
    // Assuming strings for the data types,
    // but an enum might be more appropriate.
    private String condition;
    private String result;

    public ConditionResult(String condition, String result)
    {
        this.condition = condition;
        this.result = result;
    }

    public String getCondition() { return condition; }
    public String getResult() { return result; }

    public boolean equals(Object object)
    {
        if (this == object) return true;
        if (object == null) return false;
        if (getClass() != object.getClass()) return false;
        ConditionResult other = (ConditionResult) object;
        if (condition == null)
        {
            if (other.condition != null) return false;
        } else if (!condition.equals(other.condition)) return false;
        if (result == null)
        {
            if (other.result != null) return false;
        } else if (!result.equals(other.result)) return false;

        return true;
    }

    // Need to implement hashCode as well, for equals consistency...

}


Iteration and counting could be done as:

/**
 * Count the instances of condition to result in the supplied results list
 */
public int countInstances(List<ConditionResult> results, String condition, String result)
{
    int count = 0;
    ConditionResult match = new ConditionResult(condition,result);
    for (ConditionResult result : results)
    {
        if (match.equals(result)) count++;
    }

    return count;
}

Upvotes: 0

amit
amit

Reputation: 178531

You can use a Map<T,List<U>> (in your case it is Map<String,List<String>>) or you can use a Multimap<String,String> using some library such as guava (or apache commons version of it - MultiMap)

Upvotes: 1

Related Questions