|
1 | | -package com.zetcode; |
2 | | - |
3 | | -import java.util.ArrayList; |
4 | 1 | import java.util.List; |
5 | 2 |
|
6 | | -public class UniqueNames { |
| 3 | +void main() { |
| 4 | + |
| 5 | + List<String> names = List.of("Martin", "Lucy", "Peter", |
| 6 | + "Martin", "Robert", "Peter"); |
| 7 | + |
| 8 | + System.out.println(unique(names)); |
| 9 | + System.out.println(unique2(names)); |
| 10 | + System.out.println(unique3(names)); |
| 11 | +} |
| 12 | + |
| 13 | +List<String> unique(List<String> names) { |
| 14 | + |
| 15 | + List<String> uniqueNames = new ArrayList<>(); |
7 | 16 |
|
8 | | - public static void main(String[] args) { |
| 17 | + names.forEach(e -> { |
9 | 18 |
|
10 | | - List<String> names = List.of("Martin", "Lucy", "Peter", |
11 | | - "Martin", "Robert", "Peter"); |
| 19 | + if (!uniqueNames.contains(e)) { |
12 | 20 |
|
13 | | - List<String> uniqueNames = new ArrayList<>(); |
| 21 | + uniqueNames.add(e); |
| 22 | + } |
| 23 | + }); |
14 | 24 |
|
15 | | - names.forEach(e -> { |
| 25 | + return uniqueNames; |
| 26 | +} |
| 27 | + |
| 28 | +List<String> unique2(List<String> names) { |
| 29 | + |
| 30 | + return names.stream().distinct().toList(); |
| 31 | + |
| 32 | +} |
16 | 33 |
|
17 | | - if (!uniqueNames.contains(e)) { |
| 34 | +List<String> unique3(List<String> names) { |
18 | 35 |
|
19 | | - uniqueNames.add(e); |
20 | | - } |
21 | | - }); |
| 36 | + HashSet<String> uniqueNames = new HashSet<>(names); |
22 | 37 |
|
23 | | - System.out.println(names); |
24 | | - System.out.println(uniqueNames); |
| 38 | + return new ArrayList<String>(uniqueNames); |
25 | 39 |
|
26 | | - } |
27 | 40 | } |
0 commit comments