java 判断list对象中的一个属性值是否相同

要判断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

可以使用Java的Stream API来实现这个功能。具体实现方法如下: 1. 使用Stream的map方法将集合对象转化成属性的集合; 2. 使用Stream的distinct方法去重; 3. 使用Stream的count方法统计去重后的元素个数,如果为1则说明两个集合对象某个属性全部相等,否则不相等。 示例代码如下: ```java public static boolean isPropertyEqual(List<?> list1, List<?> list2, String propertyName) { // 将集合对象转化成属性的集合 List<Object> propertyList1 = list1.stream().map(obj -> { try { Field field = obj.getClass().getDeclaredField(propertyName); field.setAccessible(true); return field.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return null; } }).collect(Collectors.toList()); // 将集合对象转化成属性的集合 List<Object> propertyList2 = list2.stream().map(obj -> { try { Field field = obj.getClass().getDeclaredField(propertyName); field.setAccessible(true); return field.get(obj); } catch (NoSuchFieldException | IllegalAccessException e) { e.printStackTrace(); return null; } }).collect(Collectors.toList()); // 去重 propertyList1 = propertyList1.stream().distinct().collect(Collectors.toList()); propertyList2 = propertyList2.stream().distinct().collect(Collectors.toList()); // 统计去重后的元素个数,如果为1则说明两个集合对象某个属性全部相等,否则不相等 return propertyList1.size() == 1 && propertyList2.size() == 1 && propertyList1.get(0).equals(propertyList2.get(0)); } ``` 其list1和list2分别表示两个集合,propertyName表示要比较的属性名。返回一个布尔,表示两个集合对象某个属性是否全部相等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值