Apache Commons libraries

In our daily work, we often use open source toolkits such as String, Date and so on. Sometimes we are not aware of the existence of these utility classes, resulting in wasted time and poor quality code being reimplemented during development. In fact, Apache has provided a series of toolkits for us to use, but most people, usually do not notice. In this series I’ll walk you through the common toolkits, familiarizing you with the common utility classes and methods that Apache provides…

names role
BeanUtils Perform various operations on Java beans, copy objects, and properties
Codec Deal with common encoding, decoding
Collections Operations that extend the Java Collections framework
I/O Encapsulation of input/output tools
Lang Java base object (java.lang) method utility class package

1 BeanUtils

BeanUtils provides a wrapper around the Java reflection and introspection APIS, whose main purpose is to use reflection to process Javabeans’ properties. Perform various operations on Javabeans, clone objects, properties, and so on.

For example,

  • BeanUtils can assign values to Javabeans’ properties.

  • BeanUtils can copy the data of a MAP collection into a Javabean object.

  • BeanUtils can assign values to javaBean objects.

Commonly used method describe
copyProperties(Object dest, Object orig) Copy the object
copyProperty(Object bean, String name, Object value) Specifies that properties are copied to the specified object
cloneBean(Object bean) Object cloning
populate(Object bean, Map<String,? extends Object> properties) Copy map data to javabean (map key must match javabean property name)
setProperty(Object bean, String name, Object value) Sets the value of the specified property

1) Beanutils.cloneBean () We know that a JavaBean usually contains a large number of attributes, and in many cases processing of JavaBean results in a large accumulation of GET /set code, increasing the code length and difficulty in reading the code

// Create a plain Java Bean to be used as the cloned object
public class Person {
    private String name = "";
    private String email = "";

    private int age;
    // omit set,get methods
}
Copy the code
Person person = new Person();
person.setName("tom");
person.setAge(21);
try {
    / / clone
    Person person2 = (Person) BeanUtils.cloneBean(person);
    System.out.println(person2.getName() + "> >" + person2.getAge());
} catch (
        IllegalAccessException e) {
    e.printStackTrace();
} catch (InstantiationException e) {
    e.printStackTrace();
} catch (InvocationTargetException e) {
    e.printStackTrace();
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}
Copy the code
// The principle is also done through Java's reflection mechanism.
// Convert a Map object to a Bean
// The Map object's key must correspond to the Bean's properties.
Map map = new HashMap();
map.put("name"."tom");
map.put("email"."tom@");
map.put("age"."21");
// Convert the map to a Person object
Person person = new Person();
BeanUtils.populate(person, map);
// With the above line of code, the person property now has the value assigned above.
// Convert a Bean to a Map object as follows:
Map map = BeanUtils.describe(person)
Copy the code

2) BeanUtils.copyProperties()

public static void copyProperties(Object source, Object target) throws BeansException {
    copyProperties(source, target, (Class)null, (String[])null);
}
Copy the code

If you have two Javabeans with many of the same attributes, the traditional way is to assign the attributes one by one using statements like the following:

Person p = new Person();
p.setName("Ensk");
p.setAge(18);
p.setGender(1);
p.setMajor("Literature");

Teacher t = new Teacher();
t.setName(p.getName());
t.setAge(p.getAge());
t.setGender(p.getGender());
t.setMajor(p.getMajor());
Copy the code

With BeanUtils, the code is much different, as shown below:

Person p = new Person();
p.setName("Ensk");
p.setAge(18);
p.setGender(1);
p.setMajor("Literature");

Teacher t = new Teacher();

BeanUtils.copyProperties(p,t);
Copy the code

== If there are attributes with different names between Person and Teacher, BeanUtils does not handle these attributes and the program needs to handle them manually

3) Other examples

@Test
public void BeanUtilsTest(a) throws Exception {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name"."Zhang");
    map.put("age".12);
    map.put("sex"."Male");

    // Copy map data to Student
    Student stu= new Student();
    BeanUtils.populate(stu, map);
   //Student [name= Student, age=12, sex= male]
    System.out.println(stu); 

    // A copy of the object
    Student stu1 = new Student ();
    BeanUtils.copyProperties(stu , stu1 );
   //Student [name= Student, age=12, sex= male]
    System.out.println(stu1);


    // Copy the specified properties
    Student stu2 = new Student ();
    BeanUtils.copyProperty(stu2 , "name"."Bill");
    // Student [age=0, age=0, sex=null]
    System.out.println(stu2 );

    // Sets the specified properties
    BeanUtils.setProperty(stu2, "sex"."Female");
   // Student [age=0, age=0, sex= female]
    System.out.println((stu2); 

    // Clone objects
    Object object = BeanUtils.cloneBean(stu2);
   // Animal [id =0, age=0, sex= female]
    System.out.println(object); 
}
Copy the code

Note: When BeanUtils copies data, it overwrites the data regardless of whether the data has a value or not. Therefore, some requirements cannot be met. For example, when the value of the copy is null, it is not allowed to overwrite the data.

public static String[] getNullPropertyNames (Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<String>();
        for(java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) emptyNames.add(pd.getName());
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }
Copy the code

Beanutils.copyproperties (source object, new object,getNullPropertyNames (source object));

2 Codec

Codec supports plain, JSON, jSON_lines, and so on.

Some common codec implementations are provided, such as Base64, Hex, MD5,Phonetic and URLs, and so on.

/ / Base64 decoding
private static String encodeTest(String str) {
    Base64 base64 = new Base64();
    try {
        str = base64.encodeToString(str.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    System.out.println("After Base64 encoding:" + str);
    return str;
}

private static void decodeTest(String str) {
    Base64 base64 = new Base64();
    //str = Arrays.toString(Base64.decodeBase64(str));
    str = new String(Base64.decodeBase64(str));
    System.out.println("Base64 decoded:" + str);
}
Copy the code

3 Collections

Extended wrapper to java.util for manipulating collection classes such as list, set. All of the methods provided are static.

Org.apache.com mons. Collections - Commons collections a set of common custom interfaces and tools org.apache.com mons. Collections. '-' the interface of a set of classes Org.apache.com mons. Collections. Bidimap - implementation bidimap series interface to a set of classes org.apache.com mons. Collections. The buffer - a set of classes implementing the buffer interface Org.apache.com mons. Collections. Collection of Java. Util. A group of class collection interface org.apache.commons.collections.com parators - Implementing a set of classes of org.apache.com java.util.Com parator interface mons. Collections. Functors - Commons collections custom function of a set of classes Org.apache.com mons. Collections. Iterators, implement the Java. Util. The Iterator interface to a set of classes org.apache.com mons. Collections. The keyvalue - Implement collection and key/value mapping a set of classes associated org.apache.com mons. Collections. The list - Java. Util. List interface to a set of classes org.apache.com mons. Collections. The map - Implement the Map series interface to a set of classes org.apache.com mons. Collections. The set - implement set series interface to a set of classesCopy the code

The use of the sort method (to sort a collection by ascending by default, all elements in a list must implement the Comparable interface)

// Select * from list

public class TestCollection {
 public static void main(String[] args) {
 List<String> list = new ArrayList<String>();
 list.add("c");
 list.add("d");
 list.add("b");
 list.add("a"); Collections.sort(list); System.out.println(list); }}// Result: [a, B, C, d]
Copy the code

2) Reverse method

Use of the Reverse method (reversing elements in a collection)

// Need: reverse the known set list

public class TestCollection {
 public static void main(String[] args) {
 List<String> list = Arrays.asList("a b c d e f".split("")); Collections.reverse(list); System.out.println(list); }}[f, e, d, c, b, a]
Copy the code

3) Shuffle method (random ordering of elements in the set)

// Select * from list

public class TestCollection {
		 public static void main(String[] args) {
		 List<String> list = new ArrayList<String>();
		 list.add("c");
		 list.add("d");
		 list.add("b");
		 list.add("a"); Collections.shuffle(list); System.out.println(list); }}//[d, c, a, b]
Copy the code

4) Application of fill(list list,Object O) method (replace all elements in list with Object 0)

public class TestCollection {
 public static void main(String[] args) {

                List<String> list = Arrays.asList("a b c d e f".split(""));
 System.out.println(list);
 Collections.fill(list, "我"); System.out.println(list); }}[a, b, c, d, e, f]
//       [我, 我, 我, 我, 我, 我]
Copy the code

5) Use of copy (List m, List n) method (copy all elements of n into M and overwrite the corresponding index elements)

public class TestCollection {
 public static void main(String[] args) {
 List<String> m = Arrays.asList("a b c d e f".split(""));
 List<String> n = Arrays.asList("Me me me me".split("")); Collections.copy(m, n); System.out.println(m); }}// Result: [me, me, me, d, e, f]
Copy the code

6) Use of min/ Max (Collection) and min/ Max (Collection,Comparator) methods (the former adopts the natural comparison method of Collection, and the latter adopts the Comparator to compare)

public class TestCollection {

 public static void main(String[] args) {
 
 List<String> list = Arrays.asList("a b c d e f".split("")); System.out.println(Collections.min(list)); }}// Result: a
Copy the code

7) Use of indexOfSubList (List m,List m)

public class TestCollection {

 public static void main(String[] args) {
 List<String> m = Arrays.asList("a b b c b d e f".split(""));
 List<String> n = Arrays.asList("b"); System.out.println(Collections.indexOfSubList(m, n)); }}// Run result: 1
Copy the code

IndexOfSubList (List m,List m); lastIndexOfSubList (List m,List m); lastIndexOfSubList (List m,List m)

public class TestCollection {
 public static void main(String[] args) {
 List<String> m = Arrays.asList("a b b c b d e f".split(""));
 List<String> n = Arrays.asList("b"); System.out.print(Collections.indexOfSubList(m, n)); System.out.println(Collections.lastIndexOfSubList(m, n)); }}// Run result: 1 4
Copy the code

Rotate (List List,int m) rotate(List List,int m) rotate(List List,int m) rotate(List List,int m) M is negative for moving to the left, m is positive for moving to the right)

public class TestCollection {

        public static void main(String[] args) {

 List<String> list = Arrays.asList("a b c d e f".split(""));
 Collections.rotate(list, 1);
 System.out.println(list);
 Collections.rotate(list, -1); System.out.println(list); }}[f, a, b, c, d, e]

// [a, b, c, d, e, f]
Copy the code

10) Swap (List List,int I,int j)

public class TestCollection {
 public static void main(String[] args) {
 List<String> list = Arrays.asList("a b c d e f".split(""));
 Collections.swap(list, 2.3); System.out.println(list); }}[a, b, d, c, e, f]
Copy the code

11) Use of the binarySearch(Collection,Object) method (find the elements in the specified Collection, return the index of the location of the element searched)

public class TestCollection {
 public static void main(String[] args) {
 List<String> list = Arrays.asList("a b c d e f".split(""));
 int index = Collections.binarySearch(list, "d"); System.out.println(index); }}// Run result: 3
Copy the code

12) Use of the replaceAll(List List,Object old,Object new) method (replace the specified element as a new element, return true if the replaced element exists, false otherwise)

public class TestCollection {
 public static void main(String[] args) {  
 List<String> list = Arrays.asList("a b c d e f".split(""));
 System.out.println(Collections.replaceAll(list, "e"."我"));
 System.out.println(Collections.replaceAll(list, "ee"."我")); System.out.println(list); }}// Result: true
// false
// [a, b, c, d, f]
Copy the code

13 Other Examples:

/** * returns a key */ that follows the order of the keys in the set
OrderedMap map = new LinkedMap();
map.put("FIVE"."5");
map.put("SIX"."6");
map.put("SEVEN"."Seven");
map.firstKey(); // returns "FIVE"
map.nextKey("FIVE"); // returns "SIX"
map.nextKey("SIX"); // returns "SEVEN"

/** * get value from key * get key from value */
BidiMap bidi = new TreeBidiMap();
bidi.put("SIX"."6");
bidi.get("SIX");  // returns "6"
bidi.getKey("6");  // returns "SIX"
// bidi.removeValue("6"); // removes the mapping
BidiMap inverse = bidi.inverseBidiMap();  // returns a map with keys and values swapped
System.out.println(inverse);

/** * returns the same element in both sets */
List<String> list1 = new ArrayList<String>();
list1.add("1");
list1.add("2");
list1.add("3");
List<String> list2 = new ArrayList<String>();
list2.add("2");
list2.add("3");
list2.add("5");
Collection c = CollectionUtils.retainAll(list1, list2);
System.out.println(c);
Copy the code

14 summary

  • Sort operations (mainly for the List interface)
Reverse (List List) : reverses the order of the elements in the List. Shuffle (List List) : randomly sorts the elements in the List. Sort (List List) : Sort (List List, Comparator c) : custom sort(List List, Comparator C)int i, intRotate (List List, rotate) : rotate(List List, rotate) : rotate(List List, rotate) : rotate(List List, rotate)intDistance) : shifts all elements to the right to specify the lengthCopy the code
  • Find and replace (mainly for the Collection interface)

BinarySearch (List List, Object key) : uses binarySearch to obtain the index of the specified Object in the List, provided that the Collection has been sorted Max (Collection coll) : Return maximum element Max (Collection coll, Comparator comp) : Returns maximum element min(Collection coll) according to the custom Comparator: Min (Collection coll, Comparator comp) : Fill (List List, Object obj) Frequency (Collection Object O) : Returns the number of occurrences of the specified Object in the specified Collection replaceAll(List List, Object old, Object)new) : replaceCopy the code

4 I/O

Commons-io is a tool for processing IO streams. It encapsulates many methods for processing IO streams and files, greatly simplifying the code for processing IO streams and manipulating files. As you can see from the official usage documentation of common-io, it is divided into utility classes, tail classes, line iterators, file filters, file comparators, and extension streams.

Website address: commons.apache.org/proper/comm…

Download: commons.apache.org/proper/comm…

4.1 tools

FileUtils, IOUtils, FilenameUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils, FileSystemUtils FileUtils operates on the File class, IOUtils operates on IO streams, and FilenameUtils operates on File names. FileSystemUtils contains some utility methods for accessing File systems that the JDK does not provide. Currently, there is only one method available for reading free space on your hard drive. Instance as follows

Use of FileUtils:

package com.wj.test;
 
import java.io.File;
import java.io.IOException;
import java.util.List;
 
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class FileUtilsTest {
 
	private String basePath = null;
 
	@Before
	public void setUp(a) {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}
 
	@After
	public void tearDown(a) throws Exception {}/** * Copy the file *@throws IOException
	 */
	@Test
	public void testCopy(a) throws IOException {
		File srcFile = new File(basePath + "a.txt");
		File destFile = new File(basePath + "b.txt");
		FileUtils.copyFile(srcFile, destFile);
	}
	
	/** * delete file *@throws IOException
	 */
	@Test
	public void testDelete(a) throws IOException{
		File delFile = new File(basePath + "b.txt");
		FileUtils.forceDelete(delFile);
		//FileUtils.forceMkdir(delFile);
	}
	
	/** * compare file contents *@throws IOException
	 */
	@Test
	public void testCompareFile(a) throws IOException{
		File srcFile = new File(basePath + "a.txt");
		File destFile = new File(basePath + "b.txt");
		boolean result = FileUtils.contentEquals(srcFile, destFile);
		System.out.println(result);
	}
	
	/** * move file *@throws IOException
	 */
	@Test
	public void testMoveFile(a) throws IOException{
		File srcFile = new File(basePath + "b.txt");
		File destDir = new File(basePath + "move");
		FileUtils.moveToDirectory(srcFile, destDir, true);
	}
	
	/** * Read the contents of the file *@throws IOException
	 */
	@Test 
	public void testRead(a) throws IOException{
		File srcFile = new File(basePath + "a.txt");
		String content = FileUtils.readFileToString(srcFile);
		List<String> contents = FileUtils.readLines(srcFile);
		System.out.println(content);
		System.out.println("* * * * * * * * * * * * * * * * * *");
		for(String string : contents) { System.out.println(string); }}/** * Write file contents *@throws IOException
	 */
	@Test
	public void testWrite(a) throws IOException{
		File srcFile = new File(basePath + "a.txt");
		FileUtils.writeStringToFile(srcFile, "\ nyes file".true); }}Copy the code

Use FileSystemUtils:

package com.wj.test;
 
import java.io.IOException;
 
import org.apache.commons.io.FileSystemUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class FileSystemUtilsTest {
	@Before
	public void setUp(a) throws Exception {}@After
	public void tearDown(a) throws Exception {}/** * Get free disk space *@throws IOException
	 */
	@SuppressWarnings("deprecation")
	@Test
	public void testFreeSpace(a) throws IOException {
		// In bytes
		System.out.println(FileSystemUtils.freeSpace("c:\\") / 1024 / 1024 / 1024);
		System.out.println(FileSystemUtils.freeSpace("d:\\") / 1024 / 1024 / 1024);
		// in k
		System.out.println(FileSystemUtils.freeSpaceKb("e:\\") / 1024 / 1024);
		System.out.println(FileSystemUtils.freeSpaceKb("f:\\") / 1024 / 1024); }}Copy the code

4.2 the end class

Different computer architectures use different conventions for byte sorting. In so-called “low-priority” architectures (such as Intel), the lowest byte is in the lowest position in memory, and the bytes that follow are in the higher position. In “high priority” architectures (such as Motorola), the situation is reversed.

There are two related classes on this library:

EndianUtils contains sequences of bytes used to exchange Java primitives and streams.

The SwappedDataInputStream class is an instance of the DataInput interface. With it, non-local byte sequences can be read.

4.3 Line iterators

Org.apache.com mons. IO. LineIterator class provides a flexible way of interaction and based on the file. You can create an instance directly, or use the factory method of FileUtils or IOUtils as follows:

package com.wj.test;
 
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class LineIteratorTest {
	
	private String basePath = null;
 
	@Before
	public void setUp(a) throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}
 
	@After
	public void tearDown(a) throws Exception {}/** * test line iterator *@throws IOException
	 */
	@Test
	public void testIterator(a) throws IOException{
		File file = new File(basePath + "a.txt");
		LineIterator li = FileUtils.lineIterator(file);
		while(li.hasNext()){ System.out.println(li.nextLine()); } LineIterator.closeQuietly(li); }}Copy the code

4.4 File Filters

Org.apache.com mons. IO. Filefilter merged package defines a Java IO. Filefilter and Java. IO. FilenameFilter interface (IOFileFilter). In addition, the package also provides a series of directly available IOFileFilter implementation classes that can be used to incorporate other file filters. For example, these file filters can be used when listing files or when using file dialogs. Examples are as follows:

package com.wj.test;
 
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.filefilter.EmptyFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class FileFilterTest {
	
	private String basePath = null;
 
	@Before
	public void setUp(a) throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}
 
	@After
	public void tearDown(a) throws Exception {}/** * Empty content file filter *@throws IOException
	 */
	@Test
	public void testEmptyFileFilter(a) throws IOException{
		File dir = new File(basePath);
		String[] files = dir.list(EmptyFileFilter.NOT_EMPTY);
		for(String file : files) { System.out.println(file); }}/** * File name suffix filter *@throws IOException
	 */
	@Test
	public void testSuffixFileFilter(a) throws IOException{
		File dir = new File(basePath);
		String[] files = dir.list(new SuffixFileFilter("a.txt"));
		for(String file : files) { System.out.println(file); }}}Copy the code

4.5 File comparator

Org.apache.commons.io.com parator package for Java. IO. File provides some java.util.Com parator interface implementation. For example, you can use these comparators to sort collections of files or arrays. Examples are as follows:

package com.wj.test;
 
import java.io.File;
import java.io.IOException;
 
import org.apache.commons.io.comparator.CompositeFileComparator;
import org.apache.commons.io.comparator.DirectoryFileComparator;
import org.apache.commons.io.comparator.NameFileComparator;
import org.apache.commons.io.comparator.PathFileComparator;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
 
public class ComparatorTest {
 
	private String basePath = null;
 
	@Before
	public void setUp(a) throws Exception {
		basePath = System.getProperty("user.dir") + "\\file\\";
	}
 
	@After
	public void tearDown(a) throws Exception {}/** * File name comparator *@throws IOException
	 */
	@Test
	public void testNameFileComparator(a) throws IOException {
		File f1 = new File(basePath + "a.txt");
		File f2 = new File(basePath + "c.txt");
		int result = NameFileComparator.NAME_COMPARATOR.compare(f1, f2);
		System.out.println(result);
	}
 
	/** * file path comparator *@throws IOException
	 */
	@Test
	public void testPathFileComparator(a) throws IOException {
		File f1 = new File(basePath + "a.txt");
		File f2 = new File(basePath + "c.txt");
		int result = PathFileComparator.PATH_COMPARATOR.compare(f1, f2);
		System.out.println(result);
	}
 
	/** * combinatorial comparator *@throws IOException
	 */
	@SuppressWarnings("unchecked")
	@Test
	public void testCompositeFileComparator(a) throws IOException {
		File dir = new File(basePath);
		File [] files = dir.listFiles();
		for (File file : files) {
			System.out.println(file.getName());
		}
		CompositeFileComparator cfc = new CompositeFileComparator(
				DirectoryFileComparator.DIRECTORY_COMPARATOR,
				NameFileComparator.NAME_COMPARATOR);
		cfc.sort(files);
		System.out.println("*****after sort*****");
		for(File file : files) { System.out.println(file.getName()); }}}Copy the code

4.6 extensions flow

Org.apache.com mons. IO. Input and org.apache.com mons. IO. The output of package contains for the realization of the data flow of all kinds of. Include:

  • Empty output stream – silently absorbs all data sent to it
  • T-shaped output streams – All two output streams are sent instead of one
  • Byte array output stream – This is a faster version of the JDK class
  • Count stream – Counts the number of bytes that pass
  • Proxy flow – Cast it the right way
  • Lockable writes – Use a locked file to provide synchronous writes
  • , etc.

The above is an excerpt from bosses article blog.csdn.net/u011179993/…

4.7 other

InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
try {  
       InputStreamReader inR = new InputStreamReader( in );  
       BufferedReader buf = new BufferedReader( inR );  
       String line;  
       while( ( line = buf.readLine() ) ! =null) { System.out.println( line ); }}finally {  
    in.close();  
  }  
  
/ / use IOUtils
  
InputStream in = new URL( "http://jakarta.apache.org" ).openStream();  
try {  
    System.out.println( IOUtils.toString( in ) );  
} finally {  
    IOUtils.closeQuietly(in);  
}  
  
/ / 2. Read the file
File file = new File("/commons/io/project.properties");  
List lines = FileUtils.readLines(file, "UTF-8");  
/ / 3. Check the remaining space
long freeSpace = FileSystemUtils.freeSpace("C:/");  
Copy the code

5 Lang

5.1 Commons-lang3 and Commons-lang differences

Lang3 is a toolkit released by the Apache Commons team that requires JDK 1.5 or older and fully supports Java5 features compared to Lang, abolishing some of the older apis. The version was not compatible with the older version, so it was renamed LANG3 to avoid conflicts

==lang package is deprecated, please do not use it in the future. Lang3 can be directly replaced by ==

5.2 package structure

org.apache.commons.lang3
 org.apache.commons.lang3.builder
 org.apache.commons.lang3.concurrent
 org.apache.commons.lang3.event
 org.apache.commons.lang3.exception
 org.apache.commons.lang3.math
 org.apache.commons.lang3.mutable
 org.apache.commons.lang3.reflect
 org.apache.commons.lang3.text
 org.apache.commons.lang3.text.translate
 org.apache.commons.lang3.time
 org.apache.commons.lang3.tuple
Copy the code

5.3 the use of

 <dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.8</version>
</dependency>
Copy the code

5.4 DateUtils

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd hh:mm:ss");

Date date = new Date();

/** * String converts to Date * arg0: the Date String String * arg1: the specific geographic, political, and cultural area. You can pass null * arg3: date format. Consistent with arg0 format String * This method interprets dates and times loosely * LOOSELY interpreted dates (such as February 42, 1996) will be treated as equivalent to the 41st day after February 1, 1996 * If strictly interpreted, such dates will raise an exception */
Date date1 = DateUtils.parseDate("20171012 14:30:12", Locale.TRADITIONAL_CHINESE, "yyyyMMdd hh:mm:ss");
Date date2 = DateUtils.parseDate("20171012 14:30:12", Locale.TRADITIONAL_CHINESE, "yyyyMMdd hh:mm:ss");

/** * String converts to Date strict * arg0: Date String String * arg1: specific geographic, political, and cultural area. You can pass null * arg3: date format. Consistent with arg0 format String * This method interprets dates and times strictly */
Date date3 = DateUtils.parseDateStrictly("20171012", Locale.TRADITIONAL_CHINESE, "yyyyMMdd");
Date date4 = DateUtils.parseDateStrictly("20171012", Locale.TRADITIONAL_CHINESE, "yyyyMMdd");

Arg0 arg1 Datatype: Date Calendar * Compare arg0 arg1 * ERA = 0 * YEAR = 1 * DAY_OF_YEAR = day of 6 */
DateUtils.isSameDay(date3, date4);
System.out.println("isSameDay = " + DateUtils.isSameDay(date3, date4));

Arg0 Arg1 Data type: Date Calendar * Whether the number of milliseconds since 00:00:00 GMT on January 1, 1970 is the same */
DateUtils.isSameInstant(date1, date2);
System.out.println("isSameInstant = " + DateUtils.isSameInstant(date1, date2));

Arg0 arg1 data type: Calendar * Compares arg0 * Data type of arg1 * ERA = YEAR 0 * YEAR = YEAR 1 * DAY_OF_YEAR = day of 6 * HOUR_OF_DAY = hour of 11 days * MINUTE = 12min * SECOND = 13sec * MILLISECOND = 14millisecond */
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(date2);
DateUtils.isSameLocalTime(cal1, cal2);
System.out.println("isSameLocalTime = " + DateUtils.isSameLocalTime(cal1, cal2));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before or after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addYears(date1, 4);
System.out.println("addYears = " + sdf.format(date));

Arg1: specifies the Date. Date type * arg1: specifies the number of days before and after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addMonths(date1, 4);
System.out.println("addMonths = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before and after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addWeeks(date1, 4);
System.out.println("addWeeks = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before and after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addDays(date1, 4);
System.out.println("addDays = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before or after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addHours(date1, 4);
System.out.println("addHours = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before or after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addMinutes(date1, 4);
System.out.println("addMinutes = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before and after the specified Date. Arg1: specifies the number of days after the specified Date
date = DateUtils.addSeconds(date1, 4);
System.out.println("addSeconds = " + sdf.format(date));

Arg0: specifies the Date. Date type * arg1: specifies the number of days before and after the specified Date. Arg1: specifies the number of days before and after the specified Date
date = DateUtils.addMilliseconds(date1, 4);
System.out.println("addMilliseconds = " + sdf.format(date));

Arg0: Date type * arg1: int type */
date = DateUtils.setYears(date1, 2008);
System.out.println("setYears = " + sdf.format(date));

Arg0: Date type arg1: int Range from 1 to 12 */
date = DateUtils.setMonths(date1, 1);
System.out.println("setMonths = " + sdf.format(date));

Arg0: Date type arg1: int Range from 1 to 31(different month values vary slightly) */
date = DateUtils.setDays(date1, 24);
System.out.println("setDays = " + sdf.format(date));

Arg0: Date type arg1: int Range from 1 to 23 */
date = DateUtils.setHours(date1, 23);
System.out.println("setHours = " + sdf.format(date));

Arg0: Date type * arg1: int Range 1 to 59 */
date = DateUtils.setMinutes(date1, 56);
System.out.println("setMinutes = " + sdf.format(date));

Arg0: Date type arg1: int Range from 1 to 59 */
date = DateUtils.setSeconds(date1, 14);
System.out.println("setMinutes = " + sdf.format(date));

Arg0: Date type * arg1: int type */
date = DateUtils.setMilliseconds(date1, 100);
System.out.println("setMinutes = " + sdf.format(date));

Calendarcal3 = calendar.getInstance (); * cal3.setTime(date); * The resulting CAL */
Calendar cal3 = DateUtils.toCalendar(date1);

TimeZone system default * timeZone1 system default timeZone * timeZone2 timeZone */
Calendar calendar = new GregorianCalendar();
TimeZone timeZone = calendar.getTimeZone();
TimeZone timeZone1 = TimeZone.getDefault();
TimeZone timeZone2 = TimeZone.getTimeZone("Europe/Copenhagen");

* arg0: Date type * arg1: time zone */
Calendar cal4 = DateUtils.toCalendar(date1, timeZone2);

long fragment = 0;

Arg0: specifies the Date type or Calendar type. Arg1: specifies the Date type or Calendar type. Specify where to start int: recommended constants like Calendar.year calendar. MONTH */
fragment = DateUtils.getFragmentInMilliseconds(date1, Calendar.MONDAY);
System.out.println("getFragmentInMilliseconds = " + fragment);

Arg0: specifies the Date type or Calendar type. Arg1: specifies the Date type or Calendar type. Specify where to start int: recommended constants like Calendar.year calendar. MONTH */
fragment = DateUtils.getFragmentInSeconds(date1, Calendar.MONDAY);
System.out.println("getFragmentInSeconds = " + fragment);

Arg0: specifies the Date type or Calendar type. Arg1: specifies the Date type or Calendar type. Specify where to start int: recommended constants like Calendar.year calendar. MONTH */
fragment = DateUtils.getFragmentInMinutes(date1, Calendar.MONDAY);
System.out.println("getFragmentInMinutes = " + fragment);

Arg0: specifies the Date type or Calendar type. Arg1: specifies the Date type. Specify where to start int: recommended constants like Calendar.year calendar. MONTH */
fragment = DateUtils.getFragmentInHours(date1, Calendar.MONDAY);
System.out.println("getFragmentInHours = " + fragment);

Arg0: specifies the Date type or Calendar type. Arg1: specifies the Date type or Calendar type. Specify where to start int: recommended constants like Calendar.year calendar. MONTH */
fragment = DateUtils.getFragmentInDays(date1, Calendar.MONDAY);
System.out.println("getFragmentInDays = " + fragment);

boolean isEquals = false;

Arg0: time 1 Date type or Calendar type arg1: Time 2 Date type or Calendar type arg2: Specify where to start comparing int types: constants such as Calendar.year calendar. MONTH are recommended
isEquals = DateUtils.truncatedEquals(date1, date2, Calendar.MONDAY);
System.out.println("truncatedEquals = " + isEquals);

int truncatedCompare = -1;

Arg0: Date type or Calendar type * arg1: Date type or Calendar type * arg2: Date type or Calendar type * arg2: Specify where to start comparing int types: constants such as Calendar.year calendar. MONTH are recommended
truncatedCompare = DateUtils.truncatedCompareTo(date1, date2, Calendar.MONDAY);
System.out.println("truncatedCompareTo = " + truncatedCompare);
Copy the code

5.5 ArrayUtils

== Is used for operations on arrays, such as add, find, delete, subarray, reverse order, element type conversion, etc. ==

It provides eight basic data types as well as wrapper classes and empty arrays of length 0 for various types. So we’re going to need an array of length 0, so instead of using new, we can just use this

public static final int[] EMPTY_INT_ARRAY = new int[0];
public static final Integer[] EMPTY_INTEGER_OBJECT_ARRAY = new Integer[0];
Copy the code
  • ToString: Functions basically the same as Java’s own Arrays.tostring method
  • HashCode: The same number of arrays in the same order will have the same hashCode
  public static void main(String[] args) {
        Integer[] inArr = new Integer[]{1.2.3};
        Integer[] inArr2 = new Integer[]{1.2.3};
        System.out.println(ArrayUtils.hashCode(inArr)); / / 862547
        System.out.println(ArrayUtils.hashCode(inArr2)); / / 862547

        inArr = new Integer[]{1.2.3};
        inArr2 = new Integer[]{1.3.3};
        System.out.println(ArrayUtils.hashCode(inArr)); / / 862547
        System.out.println(ArrayUtils.hashCode(inArr2)); / / 862584
    }
Copy the code
  • IsEquals: This method has been deprecated. Replace for Java own Java. Util. Objects. DeepEquals (Object, Object)
public static void main(String[] args) {
        Integer[] inArr = new Integer[]{1.2.3};
        Integer[] inArr2 = new Integer[]{1.2.3};
        System.out.println(Objects.deepEquals(inArr, inArr2)); //true

        inArr = new Integer[]{1.2.3};
        inArr2 = new Integer[]{1.3.3};
        System.out.println(Objects.deepEquals(inArr, inArr2)); //false
    }
Copy the code
  • ToArray: Can easily build an array. But notice the difference:
Integer[] integers = ArrayUtils.toArray(1.2.3);
        Serializable[] serializables = ArrayUtils.toArray(1.2."3");
Copy the code
  • NullToEmpty: Converts null to an empty array. If the array is not null, return the original array. If the array is null, return an empty array
  • ToObject /toPrimitive: These two methods are useful for implementing, for example, interturns between arrays of int[] and Integer[]
Integer[] inArr = new Integer[]{1.2.3};
        int[] ints = ArrayUtils.toPrimitive(inArr);
        Integer[] integers = ArrayUtils.toObject(ints);
Copy the code
  • ToStringArray: same as above. This method converts an Object array to a String array.
public static void main(String[] args) {
        Integer[] inArr = new Integer[]{1.2.3};
        int[] ints = new int[] {1.2.3};
        String[] strings = ArrayUtils.toStringArray(inArr);
        //ArrayUtils.toStringArray(ints); // Compile error
    }
Copy the code

Note:

 public static void main(String[] args) {
        Integer[] inArr = new Integer[]{1.2.null};
        //String[] strings = ArrayUtils.toStringArray(inArr);
        
        If there is a null element, an error will be reported, so we can use the following method to convert null to the specified value
        String[] strings = ArrayUtils.toStringArray(inArr,"");
        
    }
Copy the code
  • GetLength, isSameLength: sometimes recommended. Because it’s null safe. The length of null is 0

5.6 StringUtils

5.6.1 conversion

public static String rightPad(String str,int size,char padChar)It's useful when generating order numbers. The right side automatically completes. StringUtils.rightPad(null, *, *)     = null
 StringUtils.rightPad("".3.'z')     = "zzz"
 StringUtils.rightPad("bat".3.'z')  = "bat"
 StringUtils.rightPad("bat".5.'z')  = "batzz"
 StringUtils.rightPad("bat".1.'z')  = "bat"
 StringUtils.rightPad("bat", -1.'z') = "bat"
public static String leftPad(String str, int size,char padChar)
Copy the code
Stringutils. leftPad(null=, *, *)null
 StringUtils.leftPad("".3.'z')     = "zzz"
 StringUtils.leftPad("bat".3.'z')  = "bat"
 StringUtils.leftPad("bat".5.'z')  = "zzbat"
 StringUtils.leftPad("bat".1.'z')  = "bat"
 StringUtils.leftPad("bat", -1.'z') = "bat"
public static String center(String str,int size)
Copy the code
Stringutils.center (stringutils.center (null=, *)null
 StringUtils.center("".4)     = ""
 StringUtils.center("ab", -1)  = "ab"
 StringUtils.center("ab".4)   = " ab "
 StringUtils.center("abcd".2) = "abcd"
 StringUtils.center("a".4)    = " a "
public static String capitalize(String str)
Copy the code
Capitalize stringutils.capitalize (null)  = null
 StringUtils.capitalize("")    = ""
 StringUtils.capitalize("cat") = "Cat"
 StringUtils.capitalize("cAt") = "CAt"
public static String swapCase(String str)
Copy the code
Stringutils.swapcase (null)                 = null
 StringUtils.swapCase("")                   = ""
 StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
Copy the code
public static String abbreviate(String str,
                int maxWidth)An abbreviated string with three ellipses. An error is reported if maxWith is less than 3 bits. StringUtils.abbreviate(null*),      = null
 StringUtils.abbreviate("".4)        = ""
 StringUtils.abbreviate("abcdefg".6) = "abc..."
 StringUtils.abbreviate("abcdefg".7) = "abcdefg"
 StringUtils.abbreviate("abcdefg".8) = "abcdefg"
 StringUtils.abbreviate("abcdefg".4) = "a..."
 StringUtils.abbreviate("abcdefg".3) = IllegalArgumentException
public static String abbreviate(String str,
                int offset,
                int maxWidth)Some advanced uses of abbreviated strings StringUtils.abbreviate(null, *, *)                = null
 StringUtils.abbreviate("".0.4)                  = ""
 StringUtils.abbreviate("abcdefghijklmno", -1.10) = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno".0.10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno".1.10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno".4.10)  = "abcdefg..."
 StringUtils.abbreviate("abcdefghijklmno".5.10)  = "... fghi..."
 StringUtils.abbreviate("abcdefghijklmno".6.10)  = "... ghij..."
 StringUtils.abbreviate("abcdefghijklmno".8.10)  = "... ijklmno"
 StringUtils.abbreviate("abcdefghijklmno".10.10) = "... ijklmno"
 StringUtils.abbreviate("abcdefghijklmno".12.10) = "... ijklmno"
 StringUtils.abbreviate("abcdefghij".0.3)        = IllegalArgumentException
 StringUtils.abbreviate("abcdefghij".5.6)        = IllegalArgumentException
Copy the code

5.6.2 judgement

The string itself is not changed, as determined by a particular rule

1) Determine whether to include content

Note: The difference between empty and blank is that the former class returns true only when it is null or empty string, while the latter class contains all blank characters (space, TAB, newline, carriage return, etc.). You need to choose which one to use according to the purpose to be realized.

public static boolean isEmpty(CharSequence cs)One of the commonly used functions to determine whether the string is "" ornull 
StringUtils.isEmpty(null)      = true
StringUtils.isEmpty("")        = true
StringUtils.isEmpty("")       = false
StringUtils.isEmpty("bob")     = false
 
public static boolean isNotEmpty(CharSequence cs)One of the most commonly used functions, as opposed to StringUtils.isNotEmpty(null)      = false
StringUtils.isNotEmpty("")        = false
StringUtils.isNotEmpty("")       = true
StringUtils.isNotEmpty("bob")     = true
 
public static boolean isAnyEmpty(CharSequence... css)Returns if either argument is emptytrueIf none of these parameters is nullfalse. This method is useful when writing down some judgment conditions. StringUtils.isAnyEmpty(null)             = true
StringUtils.isAnyEmpty(null."foo")      = true
StringUtils.isAnyEmpty(""."bar")        = true
StringUtils.isAnyEmpty("bob"."")        = true
StringUtils.isAnyEmpty(" bob ".null)  = true
StringUtils.isAnyEmpty(""."bar")       = false
StringUtils.isAnyEmpty("foo"."bar")     = false
 
public static boolean isNoneEmpty(CharSequence... css)If either argument is null, returnfalseNone of the arguments are null, returntrueNote the use of StringUtils for these methods.isNoneEmpty(null)             = false
StringUtils.isNoneEmpty(null."foo")      = false
StringUtils.isNoneEmpty(""."bar")        = false
StringUtils.isNoneEmpty("bob"."")        = false
StringUtils.isNoneEmpty(" bob ".null)  = false
StringUtils.isNoneEmpty(""."bar")       = true
StringUtils.isNoneEmpty("foo"."bar")     = true
Copy the code
public static boolean isBlank(CharSequence cs)To determine if a character object is an empty string, note the distinction between StringUtils and isEmpty.isBlank(null)      = true
StringUtils.isBlank("")        = true
StringUtils.isBlank("")       = true
StringUtils.isBlank("bob")     = false
 
public static boolean isNotBlank(CharSequence cs) 
StringUtils.isNotBlank(null)      = false
StringUtils.isNotBlank("")        = false
StringUtils.isNotBlank("")       = false
StringUtils.isNotBlank("bob")     = trueThe principle of samepublic static boolean isAnyBlank(CharSequence... css) 
StringUtils.isAnyBlank(null)             = true
StringUtils.isAnyBlank(null."foo")      = true
StringUtils.isAnyBlank(null.null)       = true
StringUtils.isAnyBlank(""."bar")        = true
StringUtils.isAnyBlank("bob"."")        = true
StringUtils.isAnyBlank(" bob ".null)  = true
StringUtils.isAnyBlank(""."bar")       = true
StringUtils.isAnyBlank("foo"."bar")     = false
 
public static boolean isNoneBlank(CharSequence... css) 
StringUtils.isNoneBlank(null)             = false
StringUtils.isNoneBlank(null."foo")      = false
StringUtils.isNoneBlank(null.null)       = false
StringUtils.isNoneBlank(""."bar")        = false
StringUtils.isNoneBlank("bob"."")        = false
StringUtils.isNoneBlank(" bob ".null)  = false
StringUtils.isNoneBlank(""."bar")       = false
StringUtils.isNoneBlank("foo"."bar")     = true
Copy the code

2) Compare strings to equals, equalsIgnoreCase, compareTo, compareToIgnoreCase.

Extension point:

  • 1) equalsAny extension can be used for batch matching, almost not used, it is recommended to use the contains method of set more natural.
  • The override function compareTo allows you to specify the priority of null objects
public static boolean equals(CharSequence cs1, CharSequence cs2)String comparison method, is one of the more practical methods, two comparison of the string can be empty, will not report null pointer exception. StringUtils.equals(null.null)   = true
StringUtils.equals(null."abc")  = false
StringUtils.equals("abc".null)  = false
StringUtils.equals("abc"."abc") = true
StringUtils.equals("abc"."ABC") = false
public static boolean equalsIgnoreCase(CharSequence str1, CharSequence str2)A variation of the above method string comparison (ignoring case), in captcha... And so on string comparison, is really very practical. StringUtils.equalsIgnoreCase(null.null)   = true
StringUtils.equalsIgnoreCase(null."abc")  = false
StringUtils.equalsIgnoreCase("abc".null)  = false
StringUtils.equalsIgnoreCase("abc"."abc") = true
StringUtils.equalsIgnoreCase("abc"."ABC") = true
Copy the code

3) Contains strings

public static boolean contains(CharSequence seq,
               int searchChar)Whether the string seq contains searchChar StringUtils.contains(null*),    = false
StringUtils.contains(""=, *)false
StringUtils.contains("abc".'a') = true
StringUtils.contains("abc".'z') = false
public static boolean containsAny(CharSequence cs,
                  char. searchChars)Contains any object in the following arraytrue 
StringUtils.containsAny(null*),                = false
StringUtils.containsAny(""=, *)false
StringUtils.containsAny(*, null)                = false
StringUtils.containsAny(*, [])                  = false
StringUtils.containsAny("zzabyycdxx"['z'.'a']) = true
StringUtils.containsAny("zzabyycdxx"['b'.'y']) = true
StringUtils.containsAny("aba"['z'])           = false
Copy the code

4) Verify that a string is quickly returned using a series of well-implemented methods that conform to a particular rule

// Determine if only Unicode characters are included (note: Chinese characters are also Unicode characters)
public static boolean isAlpha(CharSequence cs)
// Determine if only Unicode characters and Spaces are included
public static boolean isAlphaSpace(CharSequence cs)
// Determine if only Unicode characters and numbers are included
public static boolean isAlphanumeric(CharSequence cs)
// Determine if only Unicode characters, digits, and Spaces are included
public static boolean isAlphanumericSpace(CharSequence cs)
// Check whether only numbers and Spaces are included
public static boolean isNumericSpace(CharSequence cs)
// Determine if only printable ASCII characters are included (note that Spaces are excluded)
public static boolean isAsciiPrintable(CharSequence cs)
// Check whether it is a number (note: the decimal point and the positive and negative sign are both false)
public static boolean isNumeric(CharSequence cs)
// Determine if only whitespace characters are included
public static boolean isWhitespace(CharSequence cs)
// Check whether all caps are used
public static boolean isAllUpperCase(CharSequence cs)
// Check whether all the values are lowercase
public static boolean isAllLowerCase(CharSequence cs)
// Determine whether to mix case and case (note: other characters, such as Spaces, do not affect the result)
public static boolean isMixedCase(CharSequence cs)
Copy the code

The sample

public static boolean isAlpha(CharSequence cs)Determines whether the string consists of letters StringUtils.isAlpha(null)   = false
 StringUtils.isAlpha("")     = false
 StringUtils.isAlpha("")   = false
 StringUtils.isAlpha("abc")  = true
 StringUtils.isAlpha("ab2c") = false
 StringUtils.isAlpha("ab-c") = false
Copy the code

5) Determination of start and end characters

//startWith
public static boolean startsWith(CharSequence str,CharSequence prefix)
public static boolean startsWithIgnoreCase(CharSequence str,CharSequence prefix)
public static boolean startsWithAny(CharSequence sequence,CharSequence... searchStrings)
//endWith
public static boolean endsWith(CharSequence str,CharSequence suffix)
public static boolean endsWithIgnoreCase(CharSequence str,CharSequence suffix)
public static boolean endsWithAny(CharSequence sequence,CharSequence... searchStrings)
Copy the code

5.6.3 processing

Do not change the substance of the string, and handle the beginning, end, and middle whitespace characters

1) Remove whitespace characters

== Removes whitespace from both sides of the page, and provides two classes of methods, strip and trim. Trim does not differ from the JDK in that it removes control characters (including ASCII <=32) and nulls. The Strip class, however, has been enhanced to implement many other functions through overloaded methods. It is recommended to use the Strip class in development.

Note: Full – corner Spaces are not within the scope of processing. Signature:

public static String trim(String str)Removes empty strings at both ends of strings, tabschar <= 32For example, if \n \t is empty, return null if""  
StringUtils.trim(null)          = null
StringUtils.trim("")            = ""
StringUtils.trim("")       = ""
StringUtils.trim("abc")         = "abc"
StringUtils.trim(" abc ") = "abc"Variants arepublic static String trimToNull(String str)
public static String trimToEmpty(String str)
Copy the code
Not commonly used, similar to trim() methodpublic static String strip(String str)
public static String strip(String str, String stripChars)STR: string to be processed, null stripChars: deleted string, StringUtils.strip(null*),          = null
StringUtils.strip(""=, *)""
StringUtils.strip("abc".null)      = "abc"
StringUtils.strip(" abc".null)    = "abc"
StringUtils.strip("abc ".null)    = "abc"
StringUtils.strip(" abc ".null)    = "abc"
StringUtils.strip(" abcyx"."xyz") = " abc"
Copy the code
public static String deleteWhitespace(String str)
// A compound application of basic string processing to remove all whitespace characters from a stringDelete the space StringUtils.deleteWhitespace(null)         = null
StringUtils.deleteWhitespace("")           = ""
StringUtils.deleteWhitespace("abc")        = "abc"
StringUtils.deleteWhitespace(" ab c ") = "abc"

public static String normalizeSpace(String str)
// The official example is to convert 'a' into 'A', which is very rare and will not be used. It is not sure whether the phonetic symbols of Hanyu Pinyin can be handled
public static String stripAccents(String input)
Copy the code
public static String removeStart(String str, String remove)
                 // Remove the first and last whitespace characters, but replace them with a single spaceDeletes a string that begins with a particular string, or does not delete it if there is none. StringUtils.removeStart(null*),      = null
 StringUtils.removeStart(""=, *)""
 StringUtils.removeStart(*, null)      = *
 StringUtils.removeStart("www.domain.com"."www.")   = "domain.com"
 StringUtils.removeStart("domain.com"."www.")       = "domain.com"
 StringUtils.removeStart("www.domain.com"."domain") = "www.domain.com"
 StringUtils.removeStart("abc"."")    = "abc"
Copy the code

2) To remove the end of a newline, including three cases \r\n \r\n

public static String chomp(String str)Sample StringUtils.chomp("\r") = ""
StringUtils.chomp("\n") = ""
StringUtils.chomp("\r\n") = ""
StringUtils.chomp("abc \r") = "abc "
StringUtils.chomp("abc\n") = "abc"
StringUtils.chomp("abc\r\n") = "abc"
StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
StringUtils.chomp("abc\n\r") = "abc\n"
StringUtils.chomp("abc\n\rabc") = "abc\n\rabc"
Copy the code

3) Remove spacer remove the last character. The common usage scenario is the string assembled with spacer through loop processing. Remove spacer Note: When using spacer, ensure that the last bit must be spacer, otherwise normal data may be damaged

public static String chop(String str)Example: the StringUtils.chop("1, 2, 3,") = "1, 2, 3"
StringUtils.chop("a") = ""
StringUtils.chop("abc") = "ab"
StringUtils.chop("abc\nabc") = "abc\nab"
Copy the code

// In addition, the trailing newline character is also considered as a character. If the ending is \r\n, it is removed altogether. It is recommended to use a dedicated chomp to avoid unexpected results

StringUtils.chop("\r") = ""
StringUtils.chop("\n") = ""
StringUtils.chop("\r\n") = ""
Copy the code

4) Remove all non-numeric characters and concatenate the remaining numeric characters into a string

public static String getDigits(String str)Example: the StringUtils.getDigits("abc") = ""
StringUtils.getDigits("1000$") = "1000"
StringUtils.getDigits("1123~45") = "112345"
StringUtils.getDigits("(541) 754-3010") = "5417543010"
Copy the code

5.6.4 lookup

public static int indexOf(CharSequence seq,
          int searchChar)IndexOf (StringUtils) : indexOf (StringUtils) : indexOf (StringUtils) : indexOf (StringUtils)indexOf(null*),         = -1
StringUtils.indexOf("", *)           = -1
StringUtils.indexOf("aabaabaa".'a') = 0
StringUtils.indexOf("aabaabaa".'b') = 2
public static int ordinalIndexOf(CharSequence str,
                 CharSequence searchStr,
                 int ordinal)String StringUtils is the position of the Ordinal occurrence in another string.ordinalIndexOf(null, *, *)          = -1
StringUtils.ordinalIndexOf(*, null, *)          = -1
StringUtils.ordinalIndexOf("".""=, *)0
StringUtils.ordinalIndexOf("aabaabaa"."a".1)  = 0
StringUtils.ordinalIndexOf("aabaabaa"."a".2)  = 1
StringUtils.ordinalIndexOf("aabaabaa"."b".1)  = 2
StringUtils.ordinalIndexOf("aabaabaa"."b".2)  = 5
StringUtils.ordinalIndexOf("aabaabaa"."ab".1) = 1
StringUtils.ordinalIndexOf("aabaabaa"."ab".2) = 4
StringUtils.ordinalIndexOf("aabaabaa"."".1)   = 0
StringUtils.ordinalIndexOf("aabaabaa"."".2)   = 0
 
public static int lastIndexOf(CharSequence seq,
              int searchChar)The location of the string's last occurrence StringUtils.lastIndexOf(null*),         = -1
StringUtils.lastIndexOf("", *)           = -1
StringUtils.lastIndexOf("aabaabaa".'a') = 7
StringUtils.lastIndexOf("aabaabaa".'b') = 5
public static int lastOrdinalIndexOf(CharSequence str,
                     CharSequence searchStr,
                     int ordinal)The string searchStr is the position StringUtils where the penultimate ordinal appears in STR.lastOrdinalIndexOf(null, *, *)          = -1
StringUtils.lastOrdinalIndexOf(*, null, *)          = -1
StringUtils.lastOrdinalIndexOf("".""=, *)0
StringUtils.lastOrdinalIndexOf("aabaabaa"."a".1)  = 7
StringUtils.lastOrdinalIndexOf("aabaabaa"."a".2)  = 6
StringUtils.lastOrdinalIndexOf("aabaabaa"."b".1)  = 5
StringUtils.lastOrdinalIndexOf("aabaabaa"."b".2)  = 2
StringUtils.lastOrdinalIndexOf("aabaabaa"."ab".1) = 4
StringUtils.lastOrdinalIndexOf("aabaabaa"."ab".2) = 1
StringUtils.lastOrdinalIndexOf("aabaabaa"."".1)   = 8
StringUtils.lastOrdinalIndexOf("aabaabaa"."".2)   = 8
Copy the code

extension

// Add ignoring case control
public static int indexOfIgnoreCase(CharSequence str,CharSequence searchStr)
// Return the number of indexes for the NTH match.
public static int ordinalIndexOf(CharSequence str,CharSequence searchStr,int ordinal)
// Find multiple characters at the same time
public static int indexOfAny(CharSequence cs,char. searchChars)
// Returns the first index location that is not in the search character range
public static int indexOfAnyBut(CharSequence cs,char. searchChars)

Copy the code

5.6.5 editor

String segmentation, merging, interception, replacement

1) Intercept strings

Substring and TRUNCate are basically used the same as JDK to handle exceptions internally

public static String substring(String str,int start)
public static String substring(String str,int start,int end)

public static String truncate(String str,int maxWidth);public static String truncate(String str,int offset,int maxWidth)
Copy the code

Extension:

// Directly implement from the left, right or middle of the specified digit, practical high
public static String left(String str,int len)
public static String right(String str,int len)
public static String mid(String str,int pos,int len) 

// Implement specific rules directly, but generally there are few applicable scenarios
// Returns the string before/after the first specified character
public static String substringBefore(String str,String separator)
public static String substringAfter(String str,String separator)
// Returns the string before and after the last specified character
public static String substringBeforeLast(String str,String separator)
public static String substringAfterLast(String str,String separator)
// Intercepts the middle part of a particular string
public static String substringBetween(String str,String tag)Example: the StringUtils.substringBetween("tagabctag"."tag") = "abc"
// Returns the string in the middle of the start and end strings, and only the first match
public static String substringBetween(String str,String open,String close)
// Returns the string in the middle of the start and end strings, and returns all matches
public static String[] substringBetween(String str,String open,String close)
Copy the code
public static String substring(String str,
               int start)String interception StringUtils.substring(null*),   = null
StringUtils.substring(""=, *)""
StringUtils.substring("abc".0)  = "abc"
StringUtils.substring("abc".2)  = "c"
StringUtils.substring("abc".4)  = ""
StringUtils.substring("abc", -2) = "bc"
StringUtils.substring("abc", -4) = "abc"
public static String left(String str,
          int len)
public static String right(String str,
           int len)
public static String mid(String str,
         int pos,
         int len)
Copy the code

2) Split the string

Split in the JDK uses regular expression matching, and the most common scenario for string splitting is the following split by spacer

String str="he,ll,o";
String [] reuslt=str.split(",");
Copy the code

The split approach also works, but it’s a bit awkward, as in StringUtils, where strings are matched instead of regular expressions

// Do not set the interval character, the default use whitespace character split
public static String[] split(String str)
public static String[] split(String str,
             String separatorChars)
// Split by interval
public static String[] splitByWholeSeparator(String str,String separator)
// limit return, greedy match
public static String[] splitByWholeSeparator(String str,String separator,intMax), for example: stringutils.split (null=, *)null
StringUtils.split("", *)           = []
StringUtils.split("abc def".null) = ["abc"."def"]
StringUtils.split("abc def"."")  = ["abc"."def"]
StringUtils.split("abc def"."") = ["abc"."def"]
StringUtils.split("ab:cd:ef".":") = ["ab"."cd"."ef"]

StringUtils.splitByWholeSeparator("ab-! -cd-! -ef"."-! -".5) = ["ab"."cd"."ef"]
StringUtils.splitByWholeSeparator("ab-! -cd-! -ef"."-! -".2) = ["ab"."cd-! -ef"]
Copy the code
// Whitespace is returned as an array element (other methods default to removing whitespace character elements)
public staticString [] splitPreserveAllTokens (String STR) example: StringUtils. SplitPreserveAllTokens ("abc def") = ["abc"."def"]
StringUtils.splitPreserveAllTokens("abc def") = ["abc".""."def"]
StringUtils.splitPreserveAllTokens(" abc ") = [""."abc".""]
// In certain scenarios, the same class is divided into an array element based on the character type. In the case of camel name, the last uppercase letter belongs to the following element instead of the preceding one
Copy the code
public staticString [] splitByCharacterTypeCamelCase (String STR) example: StringUtils. SplitByCharacterTypeCamelCase ("ab de fg") = ["ab".""."de".""."fg"]
StringUtils.splitByCharacterTypeCamelCase("ab de fg") = ["ab".""."de".""."fg"]
StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef") = ["ab".":"."cd".":"."ef"]
StringUtils.splitByCharacterTypeCamelCase("number5") = ["number"."5"]
StringUtils.splitByCharacterTypeCamelCase("fooBar") = ["foo"."Bar"]
StringUtils.splitByCharacterTypeCamelCase("foo200Bar") = ["foo"."200"."Bar"]
StringUtils.splitByCharacterTypeCamelCase("ASFRules") = ["ASF"."Rules"]
Copy the code

StringUtils uses the join method. This is a generic method. In practice, it is recommended that only String types be merged. Automatically removes whitespace characters or null elements

public static <T> String join(T... elements)String concatenates StringUtils.join(null)            = null
StringUtils.join([])              = ""
StringUtils.join([null])          = ""
StringUtils.join(["a"."b"."c"]) = "abc"
StringUtils.join([null.""."a"]) = "a"
 
public static String join(Object[] array,
          char separator)In many cases, it is useful to concatenate arrays with specific strings instead of retrieving the string StringUtils yourself.join(null*),               = null
StringUtils.join([], *)                 = ""
StringUtils.join([null*) =]""
StringUtils.join(["a"."b"."c"].'; ')  = "a; b; c"
StringUtils.join(["a"."b"."c"].null) = "abc"
StringUtils.join([null.""."a"].'; ')  = ";;a"
Copy the code

4) turn

public static String reverse(String str)String flipping StringUtils.reverse(null)  = null
 StringUtils.reverse("")    = ""
 StringUtils.reverse("bat") = "tab"

Copy the code

5) other

public static String defaultString(String str, String defaultStr)The default string, equivalent to a ternary operation, is weakly empty and returns StringUtils.defaultString(null."NULL")  = "NULL"
 StringUtils.defaultString(""."NULL")    = ""
 StringUtils.defaultString("bat"."NULL") = "bat"
Copy the code

5.7 ClassPathUtils Handles some utility classes on the classpath

toFullyQualifiedName(Class<? > context, String resourceName) returns a String concatenated by the class package name +resourceName

public static void main(String[] args) {

        String fullPath = ClassPathUtils.toFullyQualifiedName(Integer.class, "");
        System.out.println(fullPath); //java.lang.
        //fullPath = ClassPathUtils.toFullyQualifiedName(Integer.class.getPackage(), "Integer.value");
        fullPath = ClassPathUtils.toFullyQualifiedName(Integer.class, "Integer.value");
        System.out.println(fullPath); //java.lang.Integer.value
    }

Copy the code
  • ToFullyQualifiedName (Package Context, String resourceName) returns a String concatenated by the class Package name +resourceName
  • toFullyQualifiedPath(Class
    context, String resourceName) returns a String concatenated by the class package name +resourceName
  • ToFullyQualifiedPath (Package Context, String resourceName) returns a String concatenated by the class Package name +resourceName
ClassPathUtils.toFullyQualifiedPath(StringUtils.class
, "StringUtils.properties") = "org/apache/commons/lang3/StringUtils.properties"
Copy the code

5.8 CharUtils Operates on char values and Character objects

  • ToCharacterObjec /toChart: Convert a char or String to a Character object. Each turn. Character,valueOf() can also do this in many cases
  • ToIntValue: Converts char and Character to the corresponding int values
  • IsAscii series: Checks whether the character is an Ascii character

5.9 ClassUtils for Working with Java classes (there are many useful methods)

1) getShortClassName:

public static void main(String[] args) {
        System.out.println(int[].class.getSimpleName()); //int[]
        System.out.println(ClassUtils.getShortClassName(int[].class)); //int[]
        System.out.println(ClassUtils.getShortClassName(String.class)); //String
        System.out.println(ClassUtils.getShortClassName(ArrayList.class)); //ArrayList
        System.out.println(ClassUtils.getShortClassName("List")); //List
    }
Copy the code

2) getPackageName: Obtains the package name

 public static void main(String[] args) {
        System.out.println(ClassUtils.getPackageName(int[].class)); / / ""
        System.out.println(ClassUtils.getPackageName(String.class)); //java.lang
    }
Copy the code

3) getAllSuperclasses: Get all the parent classes of this class. Note: The parent class does not contain interfaces

 public static void main(String[] args) { List<Class<? >> allSuperclasses = ClassUtils.getAllSuperclasses(ArrayList.class); System.out.println(ArrayUtils.toString(allSuperclasses));//[class java.util.AbstractList, class java.util.AbstractCollection, class java.lang.Object]
    }

public static void main(String[] args) { List<Class<? >> allSuperclasses = ClassUtils.getAllSuperclasses(ArrayList.class); System.out.println(ArrayUtils.toString(allSuperclasses));//[class java.util.AbstractList, class java.util.AbstractCollection, class java.lang.Object]
        allSuperclasses = ClassUtils.getAllSuperclasses(Object.class);
        System.out.println(ArrayUtils.toString(allSuperclasses)); / / []
    }
Copy the code

GetAllInterfaces: same as above. But this method refers to the interface

4) convertClassNamesToClasses/convertClassesToClassNames knowledge meaning

public static void main(String[] args) { List<Class<? >> classes = ClassUtils.convertClassNamesToClasses(Arrays.asList("java.lang.Integer"."java.lang.int"));
        System.out.println(classes); //[class java.lang.Integer, null]
    }
Copy the code

5) isPrimitiveOrWrapper, isPrimitiveWrapper, primitiveToWrapper, primitivesToWrappers, wrapperToPrimitive Determine whether it is a basic type or a wrapper type

public static void main(String[] args) {
        System.out.println(ClassUtils.isPrimitiveOrWrapper(Integer.class)); //true
        System.out.println(ClassUtils.isPrimitiveOrWrapper(int.class)); //true

        // Check whether it is a wrapper type
        System.out.println(ClassUtils.isPrimitiveWrapper(Object.class)); //false Note that this is false
        System.out.println(ClassUtils.isPrimitiveWrapper(Integer.class)); //true
        System.out.println(ClassUtils.isPrimitiveWrapper(int.class)); //false

        // Check if it is a basic type
        System.out.println(Object.class.isPrimitive()); //false Note that this is also false
        System.out.println(Integer.class.isPrimitive()); //false
        System.out.println(int.class.isPrimitive()); //true
    }
Copy the code

IsAssignable supports classes, arrays, etc

7) isInnerClass: Checks whether a class is an inner class or a static inner class

8) getClass: The enhanced version of class.forname () can specify whether the value should initialize the Class immediately

9) Hierarchy: Obtain the inheritance structure of the class

public static void main(String[] args) { Iterable<Class<? >> hierarchy = ClassUtils.hierarchy(ArrayList.class); hierarchy.forEach(System.out::println);// Outputs the class hierarchy (default is no interface)
        //class java.util.ArrayList
        //class java.util.AbstractList
        //class java.util.AbstractCollection
        //class java.lang.Object
        hierarchy = ClassUtils.hierarchy(ArrayList.class,ClassUtils.Interfaces.INCLUDE);
        hierarchy.forEach(System.out::println);
        //class java.util.ArrayList
        //interface java.util.List
        //interface java.util.Collection
        //interface java.lang.Iterable
        //interface java.util.RandomAccess
        //interface java.lang.Cloneable
        //interface java.io.Serializable
        //class java.util.AbstractList
        //class java.util.AbstractCollection
        //class java.lang.Object
    }
Copy the code

10) RandomStringUtils: This might help when you need random strings

 public static void main(String[] args) {
        // It is a random word so it can be garbled
        String random = RandomStringUtils.random(10);
        // Random in the specified range
        String randomChars = RandomStringUtils.random(3.'a'.'b'.'c'.'d'.'e');
        // Random 10 Ascii characters
        String randomAscii = RandomStringUtils.randomAscii(10);
        // Note that this is not a random number between 5 and 10, but a random number of one length
        String randomNumeric = RandomStringUtils.randomNumeric(5.10);
        System.out.println(random); / /? ᣒ? ⍝? 䆃 ぬ
        System.out.println(randomChars); //dac
        System.out.println(randomAscii); //hpCQrtmUvi
        System.out.println(randomNumeric); / / 2580338
    }
Copy the code

5.9 SystemUtils: Defines some underlying system constants. Such as classpath, operating system, type, Java version, and so on

5.10 RandomUtils: This is not explained, if you need random numbers, use it. Int, long, flort are ok

5.11 RegExUtils: Handle string substitution with re, etc

  • removeAll
  • removeFirst
  • removePattern
  • replaceAll
  • replaceFirst

5.12 SerializationUtils: Object serialization tool.

In the days of Json, this tool is less likely to be used.

  • Clone: Copies an identical object using ByteArrayInputStream
  • Serialize (final Serializable obj, final OutputStream OutputStream) : you can serialize objects to an OutputStream
  • Byte [] serialize(Final Serializable obj) : Serialize directly to a byte array
  • Deserialize (final InputStream InputStream), deserialize(final Byte [] objectData)

5.13 SystemUtils: Defines some low-level system constants. Such as classpath, operating system, type, Java version, and so on

5.14 EnumUtils: Tools to aid in enumeration

  • GetEnum (Class enumClass, String enumName) returns an enumeration through the Class, possibly null
  • GetEnumList (Class enumClass) returns a collection of enumerations by Class
  • GetEnumMap (Class enumClass) Returns an enumeration map from the Class
  • IsValidEnum (Class enumClass, String enumName) Returns true false to verify that enumName is in the enumeration

Guava class library

  • Collection/collections
  • Cache [caching]
  • Primitives Support
  • Concurrency Libraries
  • Annotations common Annotations
  • String processing
  • The I/O, and so on.

A direct link to the Google Guava package (the most complete web)——–>>>>>

Pay attention to the public account “Programmer interview”

Reply to “interview” to get interview package!!

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times shake hands four times wave hands

2. Dream come true —– Project self-introduction

Here are the design patterns you asked for

4. Shocked! Check out this programmer interview manual!!

5. Teach you the interview “Profile” word for word

6. Nearly 30 interviews shared