java成神之——properties,lambda表达式,序列化
Properties
加载defaults.properties文件
defaults.properties内容如下
lastname=Smith
获取properties属性(defaults.properties文件和TestController文件置于同级目录)
try (InputStream bundledResource = TestController.class.getResourceAsStream("defaults.properties")) {
Properties defaults = new Properties();
defaults.load(bundledResource);
return defaults;
} catch (IOException e) {
throw new UncheckedIOException( "defaults.properties not properly packaged" + " with application", e);
}
写Properties到xml文件
Properties prop = new Properties();
prop.setProperty("name", "Steve");
prop.setProperty("color", "green");
prop.setProperty("age", "23");
File file = new File("C:\\Users\\26401\\Desktop\\defaults.properties");
if (!file.exists()){
file.createNewFile();
}
prop.storeToXML(new FileOutputStream(file), "testing properties with xml");
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>testing properties with xml</comment>
<entry key="color">green</entry>
<entry key="name">Steve</entry>
<entry key="age">23</entry>
</properties>
读Properties从xml文件
Properties prop = new Properties();
File file = new File("C:\\Users\\26401\\Desktop\\defaults.properties");
if (file.exists()){
prop.loadFromXML(new FileInputStream(file));
for (String name : prop.stringPropertyNames()){
System.out.println(name + "=" + prop.getProperty(name));
}
}else {
System.err.println("Error: No file found at: " + file);
}
Lambda表达式
自定义
Lambda表达式只能用于函数式接口
函数式接口只能包含一个抽象方法,可以有多个default和static方法,可以有多个重写对象的方法
@FunctionalInterface
interface MyFunctionalInterface {
void fn();
}
MyFunctionalInterface mfi = () -> System.out.println("函数式接口");
mfi.fn();
等价于
MyFunctionalInterface mfi = new MyFunctionalInterface() {
@Override
public void fn() {
System.out.println("函数式接口");
}
};
内置
Predicate<String> p = o -> o.isEmpty(); // 返回值类型必须是布尔值
Function<String, Boolean> f = o -> o.isEmpty(); // 返回值类型可以自定义
Consumer<String> c = o -> System.out.println(o); // 返回值类型为void
c.accept("没有返回值");
sort方法中使用Lambada
原始写法
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(2);
Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer b, Integer l){
return b.compareTo(l);
}
}); // [1,2,3]
Lambada写法
Collections.sort(list, (b, l) -> b.compareTo(l));
或者
Collections.sort(list, Comparator.comparing(Integer::valueOf));
序列化
文件序列化
public class SerialClass implements Serializable {
private static final long serialVersionUID = 1L;
}
Gson序列化
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
public class User {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
getter...
setter...
}
// 序列化成json
User user = new User(1, "小李");
Gson gson = new Gson();
String json = gson.toJson(user);
// 反序列化
User userCopy = gson.fromJson(json, User.class);
Jackson序列化
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
json字符串转对象
ObjectMapper objectMapper = new ObjectMapper();
User outputObject = objectMapper.readValue( "{\"id\":\"1\",\"name\":\"小叶\"}", User.class);
outputObject.getName();
@JsonIgnoreProperties(ignoreUnknown = true) // 忽视反序列化遇到的不认识的属性
public class User {
...
}
对象转字符串
User user = new User(1, "小李");
ObjectMapper objectMapper = new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
Comparable和Comparator
Comparable对象排序
public class User implements Comparable<User> {
private Integer id;
private String name;
public User(Integer id, String name) {
this.id = id;
this.name = name;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
@Override
public boolean equals(Object o) {
if (! (o instanceof User)) return false;
User p = (User)o;
return id.equals(p.id) && name.equals(p.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public int compareTo(User other) {
int idCompare = id.compareTo(other.id);
if (idCompare != 0) {
return idCompare;
} else {
return id.compareTo(other.id);
}
}
}
List<User> list = Arrays.asList(new User(2, "小李"), new User(3, "小李"), new User(1, "小李"));
Collections.sort(list);
Comparator对象排序
List<User> list = Arrays.asList(new User(2, "小李"), new User(3, "小张"), new User(1, "小王"));
Collections.sort(list, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
return u1.getId().compareTo(u2.getId());
}
});
Collections.sort(list,(u1, u2) -> {
return u1.getId().compareTo(u2.getId());
});
Collections.sort(list,Comparator.comparing(User::getId).thenComparing(User::getName));
结语
本文章是java成神的系列文章之一
如果你想知道,但是本文没有的,请下方留言
我会第一时间总结出来并发布填充到本文
java成神之——properties,lambda表达式,序列化的更多相关文章
- java成神之——集合框架之ArrayList,Lists,Sets
集合 集合种类 ArrayList 声明 增删改查元素 遍历几种方式 空集合 子集合 不可变集合 LinkedList Lists 排序 类型转换 取交集 移动元素 删除交集元素 Sets 集合特点 ...
- java成神之——文件IO
文件I/O Path Files File类 File和Path的区别和联系 FileFilter FileOutputStream FileInputStream 利用FileOutputStrea ...
- java成神之——ImmutableClass,null检查,字符编码,defaultLogger,可变参数,JavaScriptEngine,2D图,类单例,克隆,修饰符基本操作
ImmutableClass null检查 字符编码 default logger 函数可变参数 Nashorn JavaScript engine 执行脚本文件 改变js文件输出流 全局变量 2D图 ...
- 转载_2016,Java成神初年
原文地址:http://blog.csdn.net/chenssy/article/details/54017826 2016,Java成神初年.. -------------- 时间2016.12. ...
- Java成神路上之设计模式系列教程之一
Java成神路上之设计模式系列教程之一 千锋-Feri 在Java工程师的日常中,是否遇到过如下问题: Java 中什么叫单例设计模式?请用Java 写出线程安全的单例模式? 什么是设计模式?你是否在 ...
- java成神之——安全和密码
安全和密码 加密算法 公钥和私钥加密解密 生成私钥和公钥 加密数据 解密数据 公钥私钥生成的不同算法 密钥签名 生成加密随机数 基本用法 指定算法 加密对象 SealedObject Signatur ...
- java成神之——网络编程基本操作
网络编程 获取ip UDP程序示例 TCP程序 结语 网络编程 获取ip InetAddress id = InetAddress.getLocalHost(); // InetAddress id ...
- java成神之——MySQL Connector/J 的基本使用
使用示例 DBCP连接池 结语 使用示例 public class demo { static Connection con = null; static Statement st = null; s ...
- java成神之——线程操作
线程 Future CountDownLatch Multithreading synchronized Thread Producer-Consumer 获取线程状态 线程池 ThreadLocal ...
随机推荐
- SqlServer表死锁的解决方法
SqlServer表死锁的解决方法 前些天写一个存储过程,存储过程中使用了事务,后来我把一些代码注释掉来进行调试找错,突然发现一张表被锁住了,原来是创建事务的代码忘记注释掉.本文表锁住了的解决方法 ...
- python基础之继承原理,多态与封装
1.什么是继承? 继承是一种创建新的类的方式.class A: passclass B: pass2.如何继承---->如何寻找继承关系 现实生活中找继承关系是自下而上,在程序中写是自上而下继承 ...
- SpringCloud教程 | 第十一篇: docker部署spring cloud项目
版权声明:本文为博主原创文章,欢迎转载,转载请注明作者.原文超链接 ,博主地址:http://blog.csdn.net/forezp. http://blog.csdn.net/forezp/art ...
- 剑指Offer(第二版)面试案例:树中两个节点的最低公共祖先节点
(尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/74612786冷血之心的博客) 剑指Offer(第二版)面试案例:树 ...
- HAWQ取代传统数仓实践(十三)——事实表技术之周期快照
一.周期快照简介 周期快照事实表中的每行汇总了发生在某一标准周期,如一天.一周或一月的多个度量.其粒度是周期性的时间段,而不是单个事务.周期快照事实表通常包含许多数据的总计,因为任何与事实表时间范围一 ...
- [转]MFC 调用 printf 输出
摘自:http://blog.csdn.net/miyunhong/article/details/6704121 #include <io.h> #include <fcntl.h ...
- uid
var uid = 0 function nextUid() { return ++uid }
- linux上编写运行 dotnet core api
安装 Ubuntu dotnet core 跨平台已不再是梦,它带来的意义非凡,比如api接口可以在linux上编写及部署,也可以在windows上编写好,打包发布,然后copy到lin ...
- 【转】C# Socket编程(3)编码和解码
[转自:https://www.cnblogs.com/IPrograming/archive/2012/10/13/CSharp_Socket_3.html] 在网络通信中,很多情况下:比如说QQ聊 ...
- 真正明白c语言二级指针
指针是C语言的灵魂,我想对于一级指针大家应该都很熟悉,也经常用到:比如说对于字符串的处理,函数参数的“值,结果传递”等,对于二级指针或者多级指针,我想理解起来也是比较容易的,比如二级指针就是指向指针的 ...