title: Is there a data structure / library to do in memory olap / pivot tables in Java / Scala?
body: <h2>Relevant questions</h2>
  
  <p>This question is quite relevant, but is 2 years old: <a href="https://stackoverflow.com/questions/4510343/in-memory-olap-engine-in-java">In memory OLAP engine in Java</a> </p>
  
  <h2>Background</h2>
  
  <p>I would like to create a pivot-table like matrix from a given tabular dataset, in memory</p>
  
  <p>e.g. an age by marital status count (rows are age, columns are marital status).</p>
  
  <ul>
  <li><p><strong>The input</strong>: List of People, with age and some Boolean property (e.g. married), </p></li>
  <li><p><strong>The desired output</strong>: count of People, by age (row) and isMarried (column)</p></li>
  </ul>
  
  <h2>What I've tried (Scala)</h2>
  
  <pre><code>case class Person(val age:Int, val isMarried:Boolean)
  
  ...
  val people:List[Person] = ... //
  
  val peopleByAge = people.groupBy(_.age)  //only by age
  val peopleByMaritalStatus = people.groupBy(_.isMarried) //only by marital status
  </code></pre>
  
  <p>I managed to do it the naive way, first grouping by age, then <code>map</code> which is doing a  <code>count</code> by marital status, and outputs the result, then I <code>foldRight</code> to aggregate</p>
  
  <pre><code>TreeMap(peopleByAge.toSeq: _*).map(x =&gt; {
      val age = x._1
      val rows = x._2
      val numMarried = rows.count(_.isMarried())
      val numNotMarried = rows.length - numMarried
      (age, numMarried, numNotMarried)
  }).foldRight(List[FinalResult]())(row,list) =&gt; {
       val cumMarried = row._2+ 
          (if (list.isEmpty) 0 else list.last.cumMarried) 
       val cumNotMarried = row._3 + 
          (if (list.isEmpty) 0 else l.last.cumNotMarried) 
       list :+ new FinalResult(row._1, row._2, row._3, cumMarried,cumNotMarried) 
  }.reverse
  </code></pre>
  
  <p>I don't like the above code, it's not efficient, hard to read, and I'm sure there is a better way.</p>
  
  <h2>The question(s)</h2>
  
  <p>How do I groupBy "both"? and how do I do a count for each subgroup, e.g. </p>
  
  <blockquote>
    <p>How many people are exactly 30 years old and married?</p>
  </blockquote>
  
  <p>Another question, is how do I do a running total, to answer the question: </p>
  
  <blockquote>
    <p>How many people above 30 are married?</p>
  </blockquote>
  
  <hr>
  
  <p><strong>Edit:</strong></p>
  
  <p>Thank you for all the great answers.</p>
  
  <p>just to clarify, I would like the output to include a "table" with the following columns </p>
  
  <ul>
  <li>Age (ascending)</li>
  <li>Num Married </li>
  <li>Num Not Married </li>
  <li>Running Total Married </li>
  <li>Running Total Not Married </li>
  </ul>
  
  <p>Not only answering those specific queries, but to produce a report that will allow answering all such type of questions.</p>