您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關guava中的基礎工具有哪些,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
1. 基本工具[Basic utilities]
Optional類:
/**
* Optional 多用于map取值
* key 存在,如果是非null值,則返回原映射值;如果是null值則返回or后面的默認值
* key 不存在,返回or后面的默認值
*/
Map<String, Object> map = new HashMap<String, Object>();
map.put("aaa", 111);
map.put("bbb", 222);
map.put("ccc", 333);
map.put("ddd", 444);
System.out.println(map.get("eee")); // 返回null值
Object eee = Optional.fromNullable(map.get("eee")).or("555");
System.out.println(eee);
/*
* jdk 1.8 已經實現
* key存在, 如果defaultValue和映射的值不一樣, 則返回defaultValue, 否則返回原映射值;
* key不存在, 返回默認值
*/
Object fff = map.getOrDefault(map.get("fff"), "666");
System.out.println(fff);
// defaultValue 側重于給鍵重新賦值,Optional側重于判斷null。
結果:
null
555
666
Preconditions類:
// 用來檢查方法的入參是否符合條件 。。。。。。。。
// 主要有checkNotNull、checkArgument、checkElementIndex
public class PreconditionsTest {
public static void main(String[] args) {
PreconditionsTest prec = new PreconditionsTest();
try {
System.out.println(prec.sqrt(-3.0));
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
try {
System.out.println(prec.sum(null, 3));
} catch (NullPointerException e) {
System.out.println(e.getMessage());
}
try {
System.out.println(prec.getValue(5));
} catch (IndexOutOfBoundsException e) {
System.out.println(e.getMessage());
}
}
private int getValue(int i) {
int[] data = {11, 22, 33, 44, 55};
Preconditions.checkElementIndex(i, data.length, "Illegal Argument passed: Invalid index.");
return data[i];
}
private int sum(Integer a, Integer b) {
a = Preconditions.checkNotNull(a, "Illegal Argument passed: First parametere is Null.");
b = Preconditions.checkNotNull(b, "Illegal Argument passed: Second parametere is Null.");
return a + b;
}
private double sqrt(double v) {
Preconditions.checkArgument(v > 0.0, "Illegal Argument passed: Negative value %s.", v);
return Math.sqrt(v);
}
}
結果:
Illegal Argument passed: Negative value -3.0.
Illegal Argument passed: First parametere is Null.
Illegal Argument passed: Invalid index. (5) must be less than size (5)
Objects類:
// 主要方法有 equals、hashcode、toString、compare/compareTo、comparisonChain
public class ObjectsTest {
public static void main(String[] args) {
String testName = "root";
String realName = "root";
// 代替了testName != null && realName.equals(testName)
if (Objects.equal(testName, realName)) {
System.out.println(testName + "::" + realName);
}
Student s1 = new Student("Mbhesh", "Pcrashar", 1, "VI");
Student s2 = new Student("Mbhesh", "Pbrashar", 1, "VI");
Student s3 = new Student("Mahesh", "Parashar", 1, "VI");
Student s4 = new Student("Achesh", "Parashar", 1, "VI");
Student s5 = new Student("Suresh", null, 3, null);
List<Student> stu = new ArrayList<>();
stu.add(s1);
stu.add(s2);
stu.add(s3);
stu.add(s4);
stu.add(s5);
Collections.sort(stu);
for (int i = 0; i < stu.size(); i++) {
System.out.println(stu.get(i).getFirstName() + "::" + stu.get(i).getLastName());
}
// MoreObjects.toStringHelper 輸出字符串更靈活
System.out.println(MoreObjects.toStringHelper(s1).add("Name", s1.getFirstName() + " " + s1.getLastName()).add("Class", s1.getClassName()).add("Roll No", s1.getRollNo()).toString());
System.out.println(MoreObjects.toStringHelper(s2).add("firstName", s2.getFirstName()).add("lastName", s2.getLastName()));
}
}
class Student implements Comparable<Student> {
private String firstName;
private String lastName;
private int rollNo;
private String className;
public Student(String firstName, String lastName, int rollNo, String className) {
this.firstName = firstName;
this.lastName = lastName;
this.rollNo = rollNo;
this.className = className;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return rollNo == student.rollNo &&
Objects.equal(firstName, student.firstName) &&
Objects.equal(lastName, student.lastName) &&
Objects.equal(className, student.className);
}
@Override
public int hashCode() {
return Objects.hashCode(firstName, lastName, rollNo, className);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getRollNo() {
return rollNo;
}
public void setRollNo(int rollNo) {
this.rollNo = rollNo;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public int compareTo(Student student) {
return ComparisonChain.start().compare(this.firstName, student.firstName).compare(this.lastName, student.lastName).result();
}
}
輸出結果:
root::root
Achesh::Parashar
Mahesh::Parashar
Mbhesh::Pbrashar
Mbhesh::Pcrashar
Suresh::null
Student{Name=Mbhesh Pcrashar, Class=VI, Roll No=1}
Student{firstName=Mbhesh, lastName=Pbrashar}
Ordering類:
// 可以跳過實現Comparator, 直接繼承Ordering
Ordering<String> byLengthOrdering = new Ordering<String>() {
@Override
public int compare(String str1, String str2) {
return Ints.compare(str2.length(), str1.length());
}
};
List<String> train = new ArrayList<>();
train.add("a");
train.add("aba");
train.add("abbb");
train.add("bbba");
train.add("aaaaa");
Collections.sort(train, byLengthOrdering);
System.out.println(train.toString());
結果: [aaaaa, abbb, bbba, aba, a]
//鏈式調用時,從后往前讀. 可以很容易控制null值 ........
Ordering<Fruit> fruitOrdering = Ordering.natural().nullsFirst().onResultOf(new Function<Fruit, String>() {
@Nullable
@Override
public String apply(@Nullable Fruit fruit) {
return fruit.shape;
}
});
List<Fruit> fruits = new ArrayList<Fruit>();
Fruit doubleApple = new Fruit("蘋果","橢圓");
fruits.add(doubleApple);
fruits.add(new Fruit("橘子","圓形"));
fruits.add(new Fruit("榴蓮",null));
fruits.add(doubleApple);
Collections.sort(fruits, fruitOrdering);
for (Fruit fruit : fruits) {
System.out.println(fruit.name+"::"+fruit.shape);
}
class Fruit{
String name;
@Nullable String shape;
public Fruit(String name, String shape) {
this.name = name;
this.shape = shape;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Nullable
public String getShape() {
return shape;
}
public void setShape(@Nullable String shape) {
this.shape = shape;
}
}
結果:
榴蓮::null
橘子::圓形
蘋果::橢圓
蘋果::橢圓
上述就是小編為大家分享的guava中的基礎工具有哪些了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。