Java development utility class

Posted by garty on Mon, 24 Jan 2022 01:03:51 +0100

There are many tool libraries that can greatly simplify the amount of code and improve development efficiency, but many developers don't know. These class libraries have long become the industry standard class libraries, and are also used in large companies.

1. Java's own tools and methods

1.1 the list set is spliced into comma separated strings

// How to splice the list set into comma separated strings a,b,c
List<String> list = Arrays.asList("a", "b", "c");
// The first method can use stream
String join = list.stream().collect(Collectors.joining(","));
System.out.println(join); // Output a,b,c
// The second method, in fact, String also has a join method to realize this function
String join = String.join(",", list);
System.out.println(join); // Output a,b,c

1.2 compare whether two strings are equal, ignoring case

if (strA.equalsIgnoreCase(strB)) {
  System.out.println("equal");
}

1.3 compare whether two objects are equal

When we use equals to compare whether two Objects are equal, we also need to judge the null of the object on the left, otherwise we may report a null pointer exception. We can use Java The method encapsulated by Objects under util package to compare whether they are equal

Objects.equals(strA, strB); 

The source code is like this

public static boolean equals(Object a, Object b) {
    return (a == b) || (a != null && a.equals(b));
}

1.4 intersection of two List sets

List<String> list1 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
List<String> list2 = new ArrayList<>();
list2.add("a");
list2.add("b");
list2.add("d");
list1.retainAll(list2);
System.out.println(list1); // Output [a, b]

2.apache commons tool class library

apache commons is the most powerful and widely used tool class library. There are many sub libraries in it. Here are some of the most commonly used.

2.1 commons-lang,java. Enhanced version of Lang

It is recommended to use commons Lang 3. Some APIs have been optimized. The original commons Lang has stopped updating

Maven's dependencies are:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

2.1.1 empty string

The passed parameter CharSequence type is the parent class of String, StringBuilder and StringBuffer, which can be directly null judged by the following methods. The following is the source code:

public static boolean isEmpty(final CharSequence cs) {
    return cs == null || cs.length() == 0;
}

public static boolean isNotEmpty(final CharSequence cs) {
    return !isEmpty(cs);
}

// Blank characters in the string, such as spaces, line breaks, and tabs, will be removed during blank judgment
public static boolean isBlank(final CharSequence cs) {
    final int strLen = length(cs);
    if (strLen == 0) {
        return true;
    }
    for (int i = 0; i < strLen; i++) {
        if (!Character.isWhitespace(cs.charAt(i))) {
            return false;
        }
    }
    return true;
}

public static boolean isNotBlank(final CharSequence cs) {
    return !isBlank(cs);
}

2.1.2 capitalization of initial letters

String str = "yideng";
String capitalize = StringUtils.capitalize(str);
System.out.println(capitalize); //Output Yideng

2.1.3 repeated splicing string

String str = StringUtils.repeat("ab", 2);
System.out.println(str); // Output abab

2.1.4 format date

No more handwritten SimpleDateFormat formatting is needed in the future

// Date type to String type
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
System.out.println(date); // Output 2021-05-01 01:01:01

// String type to Date type
Date date = DateUtils.parseDate("2021-05-01 01:01:01", "yyyy-MM-dd HH:mm:ss");

// Calculate the date after one hour
Date date = DateUtils.addHours(new Date(), 1);

2.1.5 temporary packaging objects

When a method needs to return two or more fields, we usually encapsulate it as a temporary object. Now we don't need it with Pair and Triple

//Return two fields
ImmutablePair<Integer, String> pair = ImmutablePair.of(1, "yideng");
System.out.println(pair.getLeft() + "," + pair.getRight()); //Output 1,yideng
//Return three fields
ImmutableTriple<Integer, String, Date> triple = ImmutableTriple.of(1, "yideng", new Date());
System.out.println(triple.getLeft() + "," + triple.getMiddle() + "," + triple.getRight()); //Output

2.2 common collections collection tool class

Maven relies on:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

2.2.1 collective empty judgment

Encapsulates the method of set empty judgment. The following is the source code:

public static boolean isEmpty(final Collection<?> coll) {
    return coll == null || coll.isEmpty();
}

public static boolean isNotEmpty(final Collection<?> coll) {
    return !isEmpty(coll);
}
// Intersection of two sets
Collection<String> collection = CollectionUtils.retainAll(listA, listB);
// Union of two sets
Collection<String> collection = CollectionUtils.union(listA, listB);
// Difference set of two sets
Collection<String> collection = CollectionUtils.subtract(listA, listB);

2.3 common bean utils operation object

Maven dependency:

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.9.4</version>
</dependency>
public class User {
    private Integer id;
    private String name;
}

Set object properties

User user = new User();
BeanUtils.setProperty(user, "id", 1);
BeanUtils.setProperty(user, "name", "yideng");
System.out.println(BeanUtils.getProperty(user, "name")); // Output yideng
System.out.println(user); // Output {"id":1,"name":"yideng"}

Object and map rotate with each other

// Object to map
Map<String, String> map = BeanUtils.describe(user);
System.out.println(map); // Output {"id":"1","name":"yideng"}
// map to object
User newUser = new User();
BeanUtils.populate(newUser, map);
System.out.println(newUser); // Output {"id":1,"name":"yideng"}

2.4 commons IO file stream processing

Maven dependency:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.8.0</version>
</dependency>

File processing

File file = new File("demo1.txt");
// read file
List<String> lines = FileUtils.readLines(file, Charset.defaultCharset());
// write file
FileUtils.writeLines(new File("demo2.txt"), lines);
// Copy file
FileUtils.copyFile(srcFile, destFile);

3. Google Guava tool class library

Maven dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>30.1.1-jre</version>
</dependency>

3.1 creating collections

List<String> list = Lists.newArrayList();
List<Integer> list = Lists.newArrayList(1, 2, 3);
// Reverse list
List<Integer> reverse = Lists.reverse(list);
System.out.println(reverse); // Output [3, 2, 1]
// There are too many elements in the list set, which can be divided into several sets, with 10 elements in each set
List<List<Integer>> partition = Lists.partition(list, 10);

Map<String, String> map = Maps.newHashMap();
Set<String> set = Sets.newHashSet();

3.2 black technology collection

3.2.1 Multimap a key can map a HashMap of multiple value s

Multimap<String, Integer> map = ArrayListMultimap.create();
map.put("key", 1);
map.put("key", 2);
Collection<Integer> values = map.get("key");
System.out.println(map); // Output {key":[1,2]}
// It can also return the bloated Map you used before
Map<String, Collection<Integer>> collectionMap = map.asMap();

How easy and concise it is to save you from creating a Map again

3.2.2 BiMap is a HashMap that cannot duplicate value s

BiMap<String, String> biMap = HashBiMap.create();
// If the value is repeated, the put method throws an exception unless the forcePut method is used
biMap.put("key","value");
System.out.println(biMap); // Output {"key":"value"}
// Since value cannot be repeated, why not implement a method to flip key/value? It already exists
BiMap<String, String> inverse = biMap.inverse();
System.out.println(inverse); // Output {"value":"key"}

This is actually a two-way mapping, which is very practical in some scenarios.

3.2.3 Table is a HashMap with two key s

// A group of users, grouped by age and gender
Table<Integer, String, String> table = HashBasedTable.create();
table.put(18, "male", "yideng");
table.put(18, "female", "Lily");
System.out.println(table.get(18, "male")); // Output yideng
// This is actually a two-dimensional Map, which can view row data
Map<String, String> row = table.row(18);
System.out.println(row); // Output {"male": "yideng", "female": "Lily"}
// View column data
Map<Integer, String> column = table.column("male");
System.out.println(column); // Output {18:"yideng"}

3.2.4 Multiset is a Set used for counting

Multiset<String> multiset = HashMultiset.create();
multiset.add("apple");
multiset.add("apple");
multiset.add("orange");
System.out.println(multiset.count("apple")); // Output 2
// View de duplicated elements
Set<String> set = multiset.elementSet();
System.out.println(set); // Output ["orange","apple"]
// You can also view elements that have not been de duplicated
Iterator<String> iterator = multiset.iterator();
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
// You can also manually set the number of occurrences of an element
multiset.setCount("apple", 5);

Topics: Java string