-
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.
6.19. Промежуточные операции. Метод distinct(). Уникальные объекты
- Loading branch information
Showing
2 changed files
with
65 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,40 @@ | ||
package ru.job4j.stream; | ||
|
||
import java.util.List; | ||
import java.util.Objects; | ||
|
||
public class DistinctForObject { | ||
|
||
public static class User { | ||
private final String name; | ||
private final int age; | ||
|
||
public User(String name, int age) { | ||
this.name = name; | ||
this.age = age; | ||
} | ||
|
||
@Override | ||
public boolean equals(Object o) { | ||
if (this == o) { | ||
return true; | ||
} | ||
if (o == null || getClass() != o.getClass()) { | ||
return false; | ||
} | ||
User user = (User) o; | ||
return age == user.age && Objects.equals(name, user.name); | ||
} | ||
|
||
@Override | ||
public int hashCode() { | ||
return Objects.hash(name, age); | ||
} | ||
} | ||
|
||
public static List<User> distinct(List<User> users) { | ||
return users.stream() | ||
.distinct() | ||
.toList(); | ||
} | ||
} |
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,25 @@ | ||
package ru.job4j.stream; | ||
|
||
import org.junit.jupiter.api.Test; | ||
|
||
import java.util.List; | ||
|
||
import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
||
public class DistinctForObjectTest { | ||
|
||
@Test | ||
public void test() { | ||
DistinctForObject.User user1 = new DistinctForObject.User("A", 20); | ||
DistinctForObject.User user2 = new DistinctForObject.User("B", 20); | ||
DistinctForObject.User user3 = new DistinctForObject.User("A", 21); | ||
DistinctForObject.User user4 = new DistinctForObject.User("A", 20); | ||
assertEquals( | ||
List.of(user1, user2, user3), | ||
DistinctForObject.distinct(List.of( | ||
user1, user2, user3, user4 | ||
)) | ||
); | ||
} | ||
|
||
} |