场景
使用 Java 7 引入的 java.util.Objects 类,它在流处理中相当有用。
Objects类提供了一些工具方法,都是public static修饰的。
注:
博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主
实现
1、equals(Object a, Object b)判断两个对象内容是否一样。
User user1 = new User(1,"张三",20);
User user2 = new User(1,"张三",20);
User user3 = new User(2,"李四",20);
System.out.println(Objects.equals("user1","user2"));//false
System.out.println(Objects.equals("user1","user1"));//true
System.out.println(Objects.equals(user1,user2));//false
System.out.println(Objects.equals(user1,user1));//true
System.out.println(Objects.equals(user1,user3));//false
System.out.println(Objects.equals(user1,null));//false
2、deepEquals(Object a, Object b) 验证两个数组是否深层相等(deep equality),该方法在数组比较中尤其有用。
String[] names1 = {"zhangsan","lisi"};
String[] names2 = {"zhangsan","lisi"};
String[] names3 = {"zhangsan","lisi","wangwu"};
System.out.println(Objects.deepEquals(names1,names2));//true
System.out.println(Objects.deepEquals(names1,names3));//false
3、hashCode(Object o)获取对象的哈希值,返回int值。
System.out.println(Objects.hashCode("aaa"));//96321
System.out.println(Objects.hashCode(1));//1
System.out.println(Objects.hashCode(user1));//717356484
4、toString(Object o)获取一个对象的字符串形式。
System.out.println(Objects.toString(1));//1
System.out.println(Objects.toString(null));//null
System.out.println(Objects.toString(user1));//com.ruoyi.demo.domain.User@2ac1fdc4
5、compare(T a, T b, Comparator<? super T> c)比较两个对象,返回int值。需要传入比较器。
Comparator<User> comparator1 = (u1, u2) -> {
if (u1.getId() == u2.getId()) {
return 1;
} else {
return 0;
}
};
System.out.println(Objects.compare(user1,user2,comparator1));//1
System.out.println(Objects.compare(user1,user3,comparator1));//0
6、isNull(Object obj)判断对象是否为null nonNull(Object obj) 是否不为null
User user4 = new User(3,"赵四",20);
User user5 = null;
System.out.println(Objects.isNull(user4));//false
System.out.println(Objects.isNull(user5));//true
System.out.println(Objects.nonNull(user4));//true
System.out.println(Objects.nonNull(user5));//false
7、requireNonNull(T obj)保证传入对象不为空,为空则抛出异常
//Objects.requireNonNull(user5);//java.lang.NullPointerException
//Objects.requireNonNull(user5,"用户不能为空");//java.lang.NullPointerException: 用户不能为空
8、从泛型列表中过滤掉空元素
public <T> List<T> getNonNullElements(List<T> list){
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
方法调用
List<String> stringList = Arrays.asList("badao", null, "de", null, "chengxvyuan");
List<String> nonNullElements = getNonNullElements(stringList);
System.out.println(nonNullElements);//[badao, de, chengxvyuan]
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/135834.html