Guava工具集使用示例3

  • ​​一、异常处理​​
  • ​​二、IO读写操作​​
  • ​​三、参数校验和Object的toString重写​​
  • ​​四、Optional空指针​​
  • ​​五、table,二维矩阵的数据结构,可存放比较复杂的结构数据​​
  • ​​5.1 demo1​​
  • ​​5.2 demo2​​
  • ​​六、增强集合操作​​
  • ​​6.1 Multiset​​

一、异常处理

public class ExcepTest {
// todo Guava异常处理样例
// @Test
// public void t3() throws IOException,SQLException{
// Lists.newArrayList(RandomUtil.randomLong(20))
// try {
// // todo 可控的异常处理
// someMethodThatCouldThrowAnything();
// } catch (IKnowWhatToDoWithThisException e) {
// handle(e);
// } catch (Throwable t) {
Throwables.throwIfInstanceOf(t, IOException.class);
Throwables.throwIfInstanceOf(t, SQLException.class);
throw new RuntimeException(t); // throw t;{}
// }
// }

@Test
public void t1() {
int a = 2019;
int b = 0;
try {
final int i = a / b;
}catch (ArithmeticException e){
throw new ServiceException("分母不能是0啊");
}
catch (Throwable t) {
final String s = Throwables.getStackTraceAsString(t);
if (s.contains("by zero")) {
throw new ServiceException("分母不能是0");
}
}
}

// todo IO流异常处理
@Test
public void test2() {
// 输入和输出都使用缓冲流
try {
FileInputStream in = new FileInputStream("D:\\temp\\a.txt");
BufferedInputStream inBuffer = new BufferedInputStream(in);
FileOutputStream out = new FileOutputStream("D:\\temp\\a_copy.txt");
BufferedOutputStream outBuffer = new BufferedOutputStream(out);
int len = 0;
byte[] bs = new byte[1024];
long begin = System.currentTimeMillis();
while ((len = inBuffer.read(bs)) != -1) {
outBuffer.write(bs, 0, len);
}
System.out.println("复制文件所需的时间:" + (System.currentTimeMillis() - begin)); // 平均时间约 200 多毫秒
inBuffer.close();
in.close();
outBuffer.close();
out.close();
} catch (FileNotFoundException f) {
throw new ServiceException("文件未找到!");
} catch (Throwable t) {
t.printStackTrace();
}
}

@Test
public void t4() {
final ArrayList<Integer> list = Lists.newArrayList(1, 2, 3, 3, 3, 5, 46, 4, 7, 8, 7);
Integer integer = null;
try {
integer = list.get(2);
final int i = integer / 0;
} catch (Throwable e) {
Throwables.throwIfInstanceOf(e,NullPointerException.class);
Throwables.throwIfInstanceOf(e,IndexOutOfBoundsException.class);
}
System.out.println(integer);
}

@Test
public void t5(){
String a = "2019-06-16 12:16:49";
LocalDateTime time = null;
try {
time = LocalDateTime.parse(a);
} catch (DateTimeParseException e){
throw new ServiceException("时间转换异常");
}catch (Throwable t) {
Throwables.throwIfInstanceOf(t, DateTimeParseException.class);
}
System.out.println(time);
}


}

二、IO读写操作

public class File_test {

// todo Guava IO读写操作
@Test
public void t1(){
String fileName = "d://temp//a.txt";
String contents = "ssssssdsd test esdf eesv";
demoFileWrite(fileName,contents);
}

@Test
public void t2() throws IOException {
String testFilePath = "d://temp//a.txt";
File testFile = new File(testFilePath);
List<String> lines = Files.readLines(testFile, Charsets.UTF_8);
for (String line : lines) {
System.out.println(line);
}
}

public void demoFileWrite(final String fileName, final String contents)
{
final File newFile = new File(fileName);
try
{
Files.write(contents.getBytes(), newFile);
}
catch (IOException fileIoEx)
{
System.err.println( "ERROR trying to write to file '" + fileName + "' - "
+ fileIoEx.toString());
}
}
}

三、参数校验和Object的toString重写

@Data
class St1 {
private String name;
private Integer age;
private String city;
}

@Data
class St2 {
private String name;
private Integer age;
private String city;

@Override
public String toString() {
return "St2{" +
"name='" + name + '\'' +
", age=" + age +
", city='" + city + '\'' +
'}';
}
}

@Data
class St3 {
private String name;
private Integer age;
private String city;

// todo guava,重写对象的toString方法,为空时忽略
@Override
public String toString() {
return MoreObjects.toStringHelper(this.getClass())
.add("city", city)
.add("name", name)
.add("age", age)
.omitNullValues().toString();
}
}

public class TestObjetcs {
@Test
public void t1() {
System.out.println("st1 = " + new St1());
System.out.println("st2 = " + new St2());

final St3 st3 = new St3();
st3.setAge(12);
System.out.println("st3 = " + st3);
}

@Test
public void t2() {
final St3 st3 = new St3();
st3.setName("zhp");
st3.setCity("bj");
st3.setAge(19);
f1(st3);
}

// todo guava 参数校验
public void f1(St3 st3) {
Preconditions.checkNotNull(st3.getName(), "name may not be null");
Preconditions.checkArgument(st3.getAge() >= 18 && st3.getAge() < 99, "age must in range (18,99)");
Preconditions.checkArgument(st3.getCity() != null && st3.getCity().length() < 10, "desc too long, max length is ", 10);

}

}

四、Optional空指针

public class Optional_ {
@Test
public void t1(){
// 初始化 List
List<String> myList = new ArrayList<>();
myList.add("Geeks");
myList.add("for");
myList.add("GeeksClasses");
myList.add(null);
myList.add("GeeksforGeeks");
myList.add("");
myList.add("Data Structures");

displayValuesUsingJavaNulls(myList); // 基础手写方法判断是否为空代码
displayValuesUsingGuavaOptional(myList); // 调用 guava Optional封装方法实现
}

// Method to display values using Java Nulls
private static void displayValuesUsingJavaNulls(List<String> myList) {
System.out.println("Displaying values using Java Nulls");
// For every String in myList
for (String str : myList) {
if (str == null || str.isEmpty()) {
System.out.println("String : Value is empty or not available");
}
else {
System.out.println("String : " + str);
}
}
System.out.println();
}

// Method to display values using Guava Optional
private static void displayValuesUsingGuavaOptional(List<String> myList) {
System.out.println("Displaying values using Guava Optional");

for (String str : myList) {
Optional<String> optionalName = Optional.ofNullable(emptyToNull(str));
System.out.println("String : " + optionalName.orElse("String : Value is empty or not available"));
}
}
}

五、table,二维矩阵的数据结构,可存放比较复杂的结构数据

5.1 demo1

// todo 这是一个二维表的数据结构,一个二维矩阵
// Table是Guava提供的一个接口 Interface Table(R,C,V),由rowKey(行)+columnKey(列)+value组成
// 适用于多个健做索引的场景
public class Table_ {
@Test
public void t1(){

Table<String, String, String> studentTable = HashBasedTable.create();
studentTable.put("CSE", "5", "Dhiman");
studentTable.put("CSE", "7", "Shubham");
studentTable.put("CSE", "9", "Abhishek");
studentTable.put("CSE", "12", "Sahil");

studentTable.put("ECE", "15", "Ram");
studentTable.put("ECE", "12", "Lube");
studentTable.put("ECE", "18", "Anmol");
studentTable.put("ECE", "20", "Akhil");
studentTable.put("ECE", "25", "Amrit");

Map<String, String> eceMap = studentTable.row("ECE");
System.out.println("List of ECE students : ");

for (Map.Entry<String, String> student : eceMap.entrySet()) {
System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue());
}

System.out.println();

Map<String, String> stuMap = studentTable.column("12");
for (Map.Entry<String, String> student : stuMap.entrySet()) {
System.out.println("Student Roll No : " + student.getKey() + ", Student Name : " + student.getValue());
}
}


}

5.2 demo2

六、增强集合操作

6.1 Multiset

public class Multiset_test {

// todo Multiset对象不是set,是一个Collection,它本质上是一个Set加一个元素计数器。
@Test
public void t1(){
Multiset multiset = HashMultiset.create();
String sentences = "this is a story, there is a good girl in the story.";
Iterable<String> words = Splitter.onPattern("[^a-z]{1,}").omitEmptyStrings().trimResults().split(sentences);
for (String word : words) {
multiset.add(word);
}
final Set set = multiset.elementSet();
final Set set1 = multiset.entrySet();
for (Object element : multiset.elementSet()) {
System.out.println((String)element + ":" + multiset.count(element));
}
}

// todo 存放POJO时,可重写POJO的equals方法,除重或者统计使用
@Test
public void t2(){
Multiset multiset = HashMultiset.create();

List<A> lists = Lists.newArrayList();
for (int i = 0; i < 11; i++) {
final A a = new A().setId(i).setName("test" + i);
lists.add(a);
}

lists.add(new A().setId(2).setName("test2"));
lists.add(new A().setId(2).setName("test222"));
for (A a: lists) {
multiset.add(a);
}

final Set set1 = multiset.elementSet();
final Set set2 = multiset.entrySet();

for (Object element : multiset.elementSet()) {
System.out.println((A)element + ":" + multiset.count(element));
}
}

}

@Data
@Accessors(chain = true)
class A{
private Integer id;
private String name;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A a = (A) o;
return Objects.equals(id, a.id);
}

@Override
public int hashCode() {
return Objects.hash(id);
}
}