title: How to sort by an indeterminate amount of variables with a Collection.sort lambda expression in Java?
body: <p>I have a class called <code>Polynomial</code> with an iterator for each of its <code>Term</code>s, which are composed of two <code>int</code>s, <code>exp</code> and <code>co</code> (exponent and coefficient). These <code>Term</code>s are sorted in descending order by <code>exp</code> (e.g. <code>5x^2 + x</code> is a possible polynomial whereas <code>x + 5x^2</code> is not). I am trying to see if the polynomials are &quot;weak sorted,&quot; which only checks the exponents of successive polynomials. For instance,</p>
  <blockquote>
  <p>4x^3 + 2.3x + 8<br>
  5x^4 + 5<br>
  4.4x^4 + 5.4x^2 + 8.2</p>
  </blockquote>
  <p>is weak sorted since the highest exponent in the first polynomial is less than the second, and the third is considered greater than the second because its second term has an x^2.<br><br>
  How can I implement this type of sorting in a Collections.sort lambda expression? I couldn't think of a way to look at each of the exponents in the Polynomial and compare them one by one. For now I just compared the first term of the first polynomial's exponent to the second's, and if those were equal, compared the cumulative sum of the exponents. This isn't correct, though, since we could have many &quot;x&quot; terms and have a higher cumulative sum than a polynomial with a single x^2 term that is considered greater than that under the correct definition. This is my incorrect method currently:</p>
  <pre><code>Collections.sort(weakSortedPolys,
                          (firstP, secondP) -&gt; firstP.termList.head.term.exp &lt; secondP.termList.head.term.exp ? -1
                                  : firstP.termList.head.term.exp &gt; secondP.termList.head.term.exp ? 1
                                          : firstP.expCumSum &lt; secondP.expCumSum ? -1
                                                  : firstP.expCumSum &gt; secondP.expCumSum ? 1 : 0);
  </code></pre>
  <p>I feel like I should loop <code>.thenComparing</code>, but I'm not sure how to do that in tandem with the lambda expression, which is a requirement for my project.</p>