Skip to content

Commit 4b4254c

Browse files
authored
Update UniqueNames.java
1 parent ddc340a commit 4b4254c

1 file changed

Lines changed: 29 additions & 16 deletions

File tree

UniqueNames.java

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,40 @@
1-
package com.zetcode;
2-
3-
import java.util.ArrayList;
41
import java.util.List;
52

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<>();
716

8-
public static void main(String[] args) {
17+
names.forEach(e -> {
918

10-
List<String> names = List.of("Martin", "Lucy", "Peter",
11-
"Martin", "Robert", "Peter");
19+
if (!uniqueNames.contains(e)) {
1220

13-
List<String> uniqueNames = new ArrayList<>();
21+
uniqueNames.add(e);
22+
}
23+
});
1424

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+
}
1633

17-
if (!uniqueNames.contains(e)) {
34+
List<String> unique3(List<String> names) {
1835

19-
uniqueNames.add(e);
20-
}
21-
});
36+
HashSet<String> uniqueNames = new HashSet<>(names);
2237

23-
System.out.println(names);
24-
System.out.println(uniqueNames);
38+
return new ArrayList<String>(uniqueNames);
2539

26-
}
2740
}

0 commit comments

Comments
 (0)