Source Code for BAEL-2534 : Determine if all elements are the same in… · initialcommit-io/tutorials@73f2a12 · GitHub
Skip to content

Commit 73f2a12

Browse files
author
caroline
committed
Source Code for BAEL-2534 : Determine if all elements are the same in a Java list
1 parent f58d4a2 commit 73f2a12

3 files changed

Lines changed: 231 additions & 0 deletions

File tree

‎core-java-collections-list/pom.xml‎

Lines changed: 7 additions & 0 deletions
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package com.baeldung.allequalelements;
2+
3+
import java.util.List;
4+
import org.apache.commons.collections4.IterableUtils;
5+
import com.google.common.base.Predicate;
6+
import com.google.common.collect.Iterables;
7+
8+
public class VerifyAllEqualListElements {
9+
10+
public boolean verifyAllEqualUsingALoop(List<String> list) {
11+
for (String s : list) {
12+
if(!s.equals(list.get(0)))
13+
return false;
14+
}
15+
return true;
16+
}
17+
18+
public boolean verifyAllEqualUsingStream(List<String> list) {
19+
return list.stream().distinct().limit(2).count() <= 1;
20+
}
21+
22+
public boolean verifyAllEqualAnotherUsingStream(List<String> list) {
23+
return list.isEmpty() || list.stream().allMatch(list.get(0)::equals);
24+
}
25+
26+
27+
public boolean verifyAllEqualUsingGuava(List<String> list) {
28+
return Iterables.all(list, new Predicate<String>() {
29+
public boolean apply(String s) {
30+
return s.equals(list.get(0));
31+
}
32+
});
33+
}
34+
35+
public boolean verifyAllEqualUsingApacheCommon(List<String> list) {
36+
return IterableUtils.matchesAll(list, new org.apache.commons.collections4.Predicate<String>() {
37+
public boolean evaluate(String s) {
38+
return s.equals(list.get(0));
39+
}
40+
});
41+
}
42+
43+
}
Lines changed: 181 additions & 0 deletions

0 commit comments

Comments
 (0)