-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package ru.job4j.lambda; | ||
|
||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
public class OptionalOrElseThrow { | ||
|
||
public record User(String login) { | ||
} | ||
|
||
public static class UserNotFoundException extends RuntimeException { | ||
} | ||
|
||
public static User orElseThrow(List<User> list, String login) { | ||
return search(list, login).orElseThrow(UserNotFoundException::new); | ||
} | ||
|
||
private static Optional<User> search(List<User> list, String login) { | ||
Optional<User> result = Optional.empty(); | ||
for (User user : list) { | ||
if (user.login().equals(login)) { | ||
result = Optional.of(user); | ||
} | ||
} | ||
return result; | ||
} | ||
} |
29 changes: 29 additions & 0 deletions
29
src/test/java/ru/job4j/lambda/OptionalOrElseThrowTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
package ru.job4j.lambda; | ||
|
||
import org.junit.Test; | ||
|
||
import java.util.List; | ||
|
||
import static org.junit.Assert.assertEquals; | ||
import static ru.job4j.lambda.OptionalOrElseThrow.User; | ||
import static ru.job4j.lambda.OptionalOrElseThrow.UserNotFoundException; | ||
|
||
public class OptionalOrElseThrowTest { | ||
|
||
@Test | ||
public void whenFound() { | ||
User u1 = new User("u1"); | ||
User u2 = new User("u2"); | ||
User u3 = new User("u3"); | ||
assertEquals(u3.login(), OptionalOrElseThrow.orElseThrow( | ||
List.of(u1, u2, u3), u3.login()).login()); | ||
} | ||
|
||
@Test(expected = UserNotFoundException.class) | ||
public void whenNotFound() { | ||
User u1 = new User("u1"); | ||
User u2 = new User("u2"); | ||
User u3 = new User("u3"); | ||
OptionalOrElseThrow.orElseThrow(List.of(u1, u2, u3), "u4"); | ||
} | ||
} |