javavaadin-gridvaadin12

Vaadin Grid: How to have a Ranking row


I'm using a grid to show rankings of players. The list is sorted by various comparators on the backend but there might be still scenarios where 2 rows have the same ranking. In the example below the first two rows should have number #1 and the last two should be both #2.

enter image description here

I implemented the ranking numbers as a column as follows:

rankings.addColumn(this::getRowIndex).setWidth("2em")
            .setResizable(true);

With this method:

private String getRowIndex(TeamHasFormatRecord thfr)
  {
    index++;
    return String.valueOf(index);
  }

Which it's a basic counter. The only way I could think of is basically getting each entry and find it's place on the list but I think that might be too heavy and won't escalate well.

Any suggestions?

Update Here's the current comparator:

    Comparator.comparingDouble((TeamHasFormatRecord thfr) -> thfr.getPoints())
              .thenComparingDouble(thfr -> thfr.getMean())
              .thenComparingDouble(thfr -> thfr.getStandardDeviation())
              .reversed()

Solution

  • This can be achieved by changing the code a little in your getRowIndex method (I named it getRanking as it is no longer a simple index). The trick is to store the thfr of the current/iterated row for the next row to compare with. If they have the same scoring, don't increment the ranking.

    // class fields
    private TeamHasFormatRecord lastIteratedThfr;
    private int ranking = 0;
    
    private String getRanking(TeamHasFormatRecord thfr)
    {
        // hasSameScore() will check for equal points, mean, and standardDerivation.
        if(lastIteratedThfr == null || !thfr.hasSameScore(lastIteratedThfr)){
            ranking++;
        }
        lastIteratedThfr = thfr; // store this thfr for the next thfr to compare to
        return String.valueOf(ranking);
    }
    

    This solution only works if you sort the grid beforehand and you don't allow resorting from user. I think you already did that.