BASE-4535: Update examples for overriding compareTo

This commit is contained in:
Daniel Strmecki 2021-01-24 16:37:24 +01:00
parent 268fe2dfe6
commit 51e2fe20b1
3 changed files with 24 additions and 9 deletions

View File

@ -10,9 +10,13 @@ public class FootballPlayer implements Comparable<FootballPlayer> {
this.goalsScored = goalsScored;
}
public String getName() {
return name;
}
@Override
public int compareTo(FootballPlayer anotherPlayer) {
return this.goalsScored - anotherPlayer.goalsScored;
return Integer.compare(this.goalsScored, anotherPlayer.goalsScored);
}
@Override

View File

@ -2,6 +2,10 @@ package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
@ -11,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class FootballPlayerUnitTest {
@Test
public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenElementsAreNotAdded() {
public void givenInconsistentCompareToAndEqualsImpl_whenUsingSortedSet_thenSomeElementsAreNotAdded() {
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 800);
@ -23,11 +27,24 @@ public class FootballPlayerUnitTest {
assertThat(set).doesNotContain(ronaldo);
}
@Test
public void givenCompareToImpl_whenUsingCustomComparator_thenComparatorLogicIsApplied() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("Modric", 100);
List<FootballPlayer> players = Arrays.asList(ronaldo, messi, modric);
Comparator<FootballPlayer> nameComparator = Comparator.comparing(FootballPlayer::getName);
Collections.sort(players, nameComparator);
assertThat(players).containsExactly(messi, modric, ronaldo);
}
@Test
public void givenCompareToImpl_whenSavingElementsInTreeMap_thenKeysAreSortedUsingCompareTo() {
FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 900);
FootballPlayer messi = new FootballPlayer("Messi", 800);
FootballPlayer modric = new FootballPlayer("modric", 100);
FootballPlayer modric = new FootballPlayer("Modric", 100);
Map<FootballPlayer, String> players = new TreeMap<>();
players.put(ronaldo, "forward");

View File

@ -2,13 +2,7 @@ package com.baeldung.compareto;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
public class HandballPlayerUnitTest {