千家信息网

guava中的基础工具有哪些

发表于:2025-01-28 作者:千家信息网编辑
千家信息网最后更新 2025年01月28日,这期内容当中小编将会给大家带来有关guava中的基础工具有哪些,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。1. 基本工具[Basic utilities]Opti
千家信息网最后更新 2025年01月28日guava中的基础工具有哪些

这期内容当中小编将会给大家带来有关guava中的基础工具有哪些,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

1. 基本工具[Basic utilities]
Optional类:
/**
* Optional 多用于map取值
* key 存在,如果是非null值,则返回原映射值;如果是null值则返回or后面的默认值
* key 不存在,返回or后面的默认值
*/
Map map = new HashMap();
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 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 {

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 byLengthOrdering = new Ordering() {
@Override
public int compare(String str1, String str2) {
return Ints.compare(str2.length(), str1.length());
}
};

List 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 fruitOrdering = Ordering.natural().nullsFirst().onResultOf(new Function() {
@Nullable
@Override
public String apply(@Nullable Fruit fruit) {
return fruit.shape;
}

});

List fruits = new ArrayList();
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中的基础工具有哪些了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注行业资讯频道。

0