要判断Java中List对象的某个属性值是否全部相同,可以使用Java 8的流(Stream)API来简化操作。以下是一个示例代码,演示如何检查一个对象列表中的某个属性是否全部相同:
java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | import java.util.List; import java.util.Objects; public class ListUtils { public static <T> boolean allSameProperty(List<T> list, Function<T, ?> propertyExtractor) { if (list == null || list.isEmpty()) { return true ; } Object firstValue = propertyExtractor.apply(list.get( 0 )); return list.stream().allMatch(item -> Objects.equals(firstValue, propertyExtractor.apply(item))); } public static void main(String[] args) { // 示例对象 class Example { private String property; public Example(String property) { this .property = property; } public String getProperty() { return property; } } // 示例列表 List<Example> examples = List.of( new Example( "value1" ), new Example( "value1" ), new Example( "value1" )); // 使用allSameProperty方法检查property属性是否全部相同 boolean allPropertiesTheSame = allSameProperty(examples, Example::getProperty); System.out.println( "All properties are the same: " + allPropertiesTheSame); } } |
在这个例子中,allSameProperty方法接受一个List和一个属性提取函数(propertyExtractor)。它首先检查列表是否为空或者null,然后提取第一个元素的属性值,并检查列表中的所有其他元素的相应属性是否等于这个值。如果所有属性都相同,它返回true,否则返回false。
转载自 https://www.cnblogs.com/shalen/p/18060950