java成神之——properties,lambda表达式,序列化

Posted 叶家伟的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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成神之——HttpURLConnection访问api

springboot成神之——拦截器

成神之Java之路

java成神之——安全和密码

java成神之——Fork/Join基本使用

java成神之——enum枚举操作