1. 程式人生 > >java成神之——properties,lambda表達式,序列化

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

from 使用 接口 rom 等價 odin lec stream map

  • Properties
    • 加載defaults.properties文件
    • 寫Properties到xml文件
    • 讀Properties從xml文件
  • Lambda表達式
    • 自定義
    • 內置
    • sort方法中使用Lambada
  • 序列化
    • 文件序列化
    • Gson序列化
    • Jackson序列化
  • Comparable和Comparator
    • Comparable對象排序
    • Comparator對象排序
  • 結語

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表達式,序列化