Skip to content

Commit e9abcca

Browse files
authored
Merge pull request #874 from sk1418/find-in-nested-list
[find-in-nested-list] find first element in list of list
2 parents 90fdb63 + 252d34d commit e9abcca

File tree

1 file changed

+91
-0
lines changed

1 file changed

+91
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
package findFirstMatchInNestedList
2+
3+
import org.junit.jupiter.api.Test
4+
import org.slf4j.Logger
5+
import org.slf4j.LoggerFactory
6+
import kotlin.test.assertEquals
7+
8+
data class Player(val name: String, val score: Int)
9+
10+
data class Team(val name: String, val players: List<Player>)
11+
12+
val teamA = Team(
13+
"Team A", listOf(
14+
Player("Sam", 7),
15+
Player("Mike", 35),
16+
Player("Vincent", 15),
17+
Player("Paul", 12)
18+
)
19+
)
20+
val teamB = Team(
21+
"Team B", listOf(
22+
Player("Tom", 50),
23+
Player("Jim", 35),
24+
Player("Kai", 150),
25+
Player("Tim", 200)
26+
)
27+
)
28+
val teamC = Team(
29+
"Team C", listOf(
30+
Player("Leo", 15),
31+
Player("Sean", 25),
32+
Player("Jack", 10),
33+
Player("Tim", 8)
34+
)
35+
)
36+
val teamD = Team(
37+
"Team D", listOf(
38+
Player("Eric", 54),
39+
Player("Liam", 104),
40+
Player("Kevin", 70),
41+
Player("Peter", 177),
42+
)
43+
)
44+
val teams = listOf(teamA, teamB, teamC, teamD)
45+
46+
class FindTheFirstMatchInNestedListUnitTest {
47+
private val log: Logger = LoggerFactory.getLogger(FindTheFirstMatchInNestedListUnitTest::class.java)
48+
49+
@Test
50+
fun `when using flatmap and first then get the expected result`() {
51+
val result = teams.flatMap { it.players }.first { it.score > 100 }
52+
assertEquals(Player("Kai", 150), result)
53+
54+
teams.flatMap {
55+
log.info("Transforming players of the team: ${it.name}")
56+
it.players
57+
}.first {
58+
log.info("Checking the player: ${it.name}")
59+
it.score > 100
60+
}
61+
}
62+
63+
@Test
64+
fun `when finding the first match using foreach then get the expected result`() {
65+
fun findTheFirstPlayerHigherThan100(teams: List<Team>): Player {
66+
teams.forEach { team ->
67+
log.info("Checking players of the team: ${team.name}")
68+
team.players.forEach { player ->
69+
log.info("|- Checking the player: ${player.name}")
70+
if (player.score > 100) return player
71+
}
72+
}
73+
throw IllegalStateException("No matched player found")
74+
}
75+
76+
val result = findTheFirstPlayerHigherThan100(teams)
77+
assertEquals(Player("Kai", 150), result)
78+
}
79+
80+
@Test
81+
fun `when using sequence and then flatmap and first then get the expected result`() {
82+
val result = teams.asSequence().flatMap {
83+
log.info("Transforming players of the team: ${it.name}")
84+
it.players
85+
}.first {
86+
log.info("|- Checking the player: ${it.name}")
87+
it.score > 100
88+
}
89+
assertEquals(Player("Kai", 150), result)
90+
}
91+
}

0 commit comments

Comments
 (0)