1. Birth background
Because the standard Java library cannot provide enough methods to manipulate its core classes. Apache Commons Lang provides these additional methods and tools.
Lang is Java Lang API provides many helper utilities, especially string operation methods, basic numerical methods, object reflection, concurrency, creation and serialization, and system properties. In addition, it also contains a reference to Java util. Basic enhancements to date, as well as a series of utilities dedicated to building methods, such as hashCode, toString and equals.
2. Introduction scheme, maven introduction method
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.10</version> </dependency>
3. Brief introduction
org.apache.commons.lang3 #Provides highly reusable static utility methods, mainly for Java Lang class adds value. org.apache.commons.lang3.arch #Provide classes to use OS The value of the arch system property. org.apache.commons.lang3.builder #Help create consistent equals (Object), toString (), hashCode (), and compareTo (Object) methods. org.apache.commons.lang3.compare #Provides classes to use comparable and comparative interfaces. org.apache.commons.lang3.concurrent #Provides support classes for multithreaded programming. org.apache.commons.lang3.event #Provides some useful event based utilities. org.apache.commons.lang3.exception #Provide abnormal functions. org.apache.commons.lang3.math #Extend Java. Net for business math classes math. org.apache.commons.lang3.mutable #Provides typed variable wrappers for primitive values and objects. org.apache.commons.lang3.reflect #Provide reflection Java Common and advanced usage of lang.reflect API. org.apache.commons.lang3.text #Provides classes for processing and manipulating text, partially used as Java Text extension. org.apache.commons.lang3.text.translate #An API for creating text conversion routines from a set of smaller building blocks. org.apache.commons.lang3.time #Provides classes and methods for processing dates and durations. org.apache.commons.lang3.tuple #Tuple class, starting with the pair class in version 3.0.
4. Common details
Common strings (StringUtils)
//Shorten to a certain length with ending. In fact, it is (substring(str, 0, max-3) + "...") //public static String abbreviate(String str,int maxWidth) StringUtils.abbreviate("abcdefg", 6);// ---"abc..." //Whether the suffix at the end of the string matches the suffix you want to end. If not, add a suffix StringUtils.appendIfMissing("abc","xyz");//---"abcxyz" StringUtils.appendIfMissingIgnoreCase("abcXYZ","xyz");//---"abcXYZ" //Initial case conversion StringUtils.capitalize("cat");//---"Cat" StringUtils.uncapitalize("Cat");//---"cat" //The string is expanded to the specified size and centered (if the expanded size is less than the original character size, the original character is returned; if the expanded size is negative, it is calculated as 0) StringUtils.center("abcd", 2);//--- "abcd" StringUtils.center("ab", -1);//--- "ab" StringUtils.center("ab", 4);//---" ab " StringUtils.center("a", 4, "yz");//---"yayz" StringUtils.center("abc", 7, "");//---" abc " //Remove "\ n", "\r", or "\r\n" from the string StringUtils.chomp("abc\r\n");//---"abc" //Determines whether a string contains another string StringUtils.contains("abc", "z");//---false StringUtils.containsIgnoreCase("abc", "A");//---true //Counts the number of occurrences of one string in another string StringUtils.countMatches("abba", "a");//---2 //There are spaces in the delete string StringUtils.deleteWhitespace(" ab c ");//---"abc" //Compare two strings and return the differences. Specifically, it returns a string in the second parameter that is different from the first parameter StringUtils.difference("abcde", "abxyz");//---"xyz" //Check whether the suffix at the end of the string matches StringUtils.endsWith("abcdef", "def");//---true StringUtils.endsWithIgnoreCase("ABCDEF", "def");//---true StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true //Check whether the starting string matches StringUtils.startsWith("abcdef", "abc");//---true StringUtils.startsWithIgnoreCase("ABCDEF", "abc");//---true StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"});//---true //Judge whether the two strings are the same StringUtils.equals("abc", "abc");//---true StringUtils.equalsIgnoreCase("abc", "ABC");//---true //Compare the character sequences of all elements in the string array. If the start is consistent, a consistent string will be returned. If there is no, a "" will be returned StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"});//---"ab" //Forward looking for the first occurrence of a character in a string StringUtils.indexOf("aabaabaa", "b");//---2 StringUtils.indexOf("aabaabaa", "b", 3);//---5 (look after corner mark 3) StringUtils.ordinalIndexOf("aabaabaa", "a", 3);//---1 (find the position of the nth occurrence) //Reverses the position where the string first appears StringUtils.lastIndexOf("aabaabaa", 'b');//---5 StringUtils.lastIndexOf("aabaabaa", 'b', 4);//---2 StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2);//---1 //Judge whether the string is uppercase or lowercase StringUtils.isAllUpperCase("ABC");//---true StringUtils.isAllLowerCase("abC");//---false //Judge whether it is empty (Note: the difference between isBlank and isEmpty) StringUtils.isBlank(null);StringUtils.isBlank("");StringUtils.isBlank(" ");//---true StringUtils.isNoneBlank(" ", "bar");//---false StringUtils.isEmpty(null);StringUtils.isEmpty("");//---true StringUtils.isEmpty(" ");//---false StringUtils.isNoneEmpty(" ", "bar");//---true //Judgment string number StringUtils.isNumeric("123");//---false StringUtils.isNumeric("12 3");//---false (do not recognize operation symbols, decimal points, spaces...) StringUtils.isNumericSpace("12 3");//---true //Add separator to array //StringUtils.join([1, 2, 3], ';');//---"1;2;3" //toggle case StringUtils.upperCase("aBc");//---"ABC" StringUtils.lowerCase("aBc");//---"abc" StringUtils.swapCase("The dog has a BONE");//---"tHE DOG HAS A bone" //Replace string contents... (replacePattern, replaceonce) StringUtils.replace("aba", "a", "z");//---"zbz" StringUtils.overlay("abcdef", "zz", 2, 4);//---"abzzef" (specify area) StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"});//---"wcte" (multiple sets of specified substitutions ab - > W, D - > t) //Repeat character StringUtils.repeat('e', 3);//---"eee" //Reverse string StringUtils.reverse("bat");//---"tab" //Delete a character StringUtils.remove("queued", 'u');//---"qeed" //Split string StringUtils.split("a..b.c", '.');//---["a", "b", "c"] StringUtils.split("ab:cd:ef", ":", 2);//---["ab", "cd:ef"] StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2);//---["ab", "cd-!-ef"] StringUtils.splitByWholeSeparatorPreserveAllTokens("ab::cd:ef", ":");//-["ab"," ","cd","ef"] //Remove the leading and trailing spaces, similar to trim... (stripStart, stripEnd, stripAll, stripAccents) StringUtils.strip(" ab c ");//---"ab c" StringUtils.stripToNull(null);//---null StringUtils.stripToEmpty(null);//---"" //Intercept string StringUtils.substring("abcd", 2);//---"cd" StringUtils.substring("abcdef", 2, 4);//---"cd" //Left and right intercept n-bit characters from left (right) StringUtils.left("abc", 2);//---"ab" StringUtils.right("abc", 2);//---"bc" //Intercept m-bit characters from the nth bit StringUtils.mid("abcdefg", 2, 4);//---"cdef" StringUtils.substringBefore("abcba", "b");//---"a" StringUtils.substringBeforeLast("abcba", "b");//---"abc" StringUtils.substringAfter("abcba", "b");//---"cba" StringUtils.substringAfterLast("abcba", "b");//---"a" StringUtils.substringBetween("tagabctag", "tag");//---"abc" StringUtils.substringBetween("yabczyabcz", "y", "z");//---"abc"
Random number generation class (RandomStringUtils)
//Randomly generate n-digit numbers RandomStringUtils.randomNumeric(n); //Generates a random string of length n in the specified string RandomStringUtils.random(n, "abcdefghijk"); //Specifies that random strings are generated from characters or numbers System.out.println(RandomStringUtils.random(n, true, false)); System.out.println(RandomStringUtils.random(n, false, true));
Digital class NumberUtils
//Select the maximum value from the array NumberUtils.max(new int[] { 1, 2, 3, 4 });//---4 //Determines whether the string is all integers NumberUtils.isDigits("153.4");//--false //Determines whether the string is a valid number NumberUtils.isNumber("0321.1");//---false
Array class ArrayUtils
//Create array String[] array = ArrayUtils.toArray("1", "2"); //Judge whether the two data are equal. If the contents are the same and the order is the same, return true ArrayUtils.isEquals(arr1,arr2); //Determine whether the array contains an object ArrayUtils.contains(arr, "33"); //Convert 2D array to MAP Map map = ArrayUtils.toMap(new String[][] { { "RED", "#FF0000" }, { "GREEN", "#00FF00" }, { "BLUE", "#0000FF" } });
Date class DateUtils
//Date plus n days DateUtils.addDays(new Date(), n); //Determine whether the same day DateUtils.isSameDay(date1, date2); //Convert string time to Date DateUtils.parseDate(str, parsePatterns);
/**
- Convert String to Date
- arg0: date String
- arg1: specific geographical, political and cultural areas Can pass null
- arg3: date format String consistent with arg0 format
- The interpretation of date and time in this method is loose
- A loose interpretation date (e.g. 42 February 1996) will be deemed to be equivalent to the 41st day after 1 February 1996
- If it is strictly interpreted, this kind of date will throw 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 to Date strict
- arg0: date String
- arg1: specific geographical, political and cultural areas Can pass null
- arg3: date format String consistent with arg0 format
- The interpretation of date and time in this method is strict
*/
Date date3 = DateUtils.parseDateStrictly("20171012", Locale.TRADITIONAL_CHINESE, "yyyyMMdd");
Date date4 = DateUtils.parseDateStrictly("20171012", Locale.TRADITIONAL_CHINESE, "yyyyMMdd");
/**
- Judge whether the two dates are the same day
- Arg0arg1data type: Date Calendar
- Compare arg0 to arg1
- ERA = 0's
- YEAR = 1 year
- DAY_ OF_ Year = the day in 6 years
*/
DateUtils.isSameDay(date3, date4);
System.out.println("isSameDay = " + DateUtils.isSameDay(date3, date4));
/**
- Judge whether the two dates are the same millisecond
- Arg0arg1data type: Date Calendar
- Are the milliseconds equal since January 1, 1970 00:00:00 GMT
*/
DateUtils.isSameInstant(date1, date2);
System.out.println("isSameInstant = " + DateUtils.isSameInstant(date1, date2));
/**
- Determine whether it is the same local time
- Arg0arg1data type: Calendar
- Compare arg0 to arg1
- data type
- ERA = 0's
- YEAR = 1 year
- DAY_ OF_ Year = the day in 6 years
- HOUR_ OF_ Day = the hour of 11 days
- MINUTE = 12 minutes
- SECOND = 13 seconds
- MILLISECOND = 14 milliseconds
*/
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));
/**
- Gets arg1 years before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addYears(date1, 4);
System.out.println("addYears = " + sdf.format(date));
/**
- Gets the month arg1 around the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addMonths(date1, 4);
System.out.println("addMonths = " + sdf.format(date));
/**
- Gets arg1 weeks before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addWeeks(date1, 4);
System.out.println("addWeeks = " + sdf.format(date));
/**
- Gets arg1 days before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addDays(date1, 4);
System.out.println("addDays = " + sdf.format(date));
/**
- Gets arg1 hours before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addHours(date1, 4);
System.out.println("addHours = " + sdf.format(date));
/**
- Gets arg1 minutes before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addMinutes(date1, 4);
System.out.println("addMinutes = " + sdf.format(date));
/**
- Gets Arg 1 seconds before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addSeconds(date1, 4);
System.out.println("addSeconds = " + sdf.format(date));
/**
- Gets arg1 milliseconds before and after the specified date
- arg0: Specify Date Type
- Arg1: int type, positive number backward days, 0 day, negative number forward days
*/
date = DateUtils.addMilliseconds(date1, 4);
System.out.println("addMilliseconds = " + sdf.format(date));
/**
- Specifies the value of the date year
- arg0: Date type
- Arg1: int type
*/
date = DateUtils.setYears(date1, 2008);
System.out.println("setYears = " + sdf.format(date));
/**
- Specifies the value of the date month
- arg0: Date type
- Arg1: int type, range 1-12
*/
date = DateUtils.setMonths(date1, 1);
System.out.println("setMonths = " + sdf.format(date));
/**
- Specifies the value of the day
- arg0: Date type
- Arg1: the int type range is 1-31 (the values are slightly different in different months)
*/
date = DateUtils.setDays(date1, 24);
System.out.println("setDays = " + sdf.format(date));
/**
- Specifies the value of the date hour
- arg0: Date type
- Arg1: int type, range 1-23
*/
date = DateUtils.setHours(date1, 23);
System.out.println("setHours = " + sdf.format(date));
/**
- Specifies the value of the date minute
- arg0: Date type
- Arg1: int type, range 1-59
*/
date = DateUtils.setMinutes(date1, 56);
System.out.println("setMinutes = " + sdf.format(date));
/**
- Specifies the value of the date second
- arg0: Date type
- Arg1: int type, range 1-59
*/
date = DateUtils.setSeconds(date1, 14);
System.out.println("setMinutes = " + sdf.format(date));
/**
- Specifies the value of the date in milliseconds
- arg0: Date type
- Arg1: int type
*/
date = DateUtils.setMilliseconds(date1, 100);
System.out.println("setMinutes = " + sdf.format(date));
/**
- amount to
- Calendar cal3 = Calendar.getInstance();
- cal3.setTime(date);
- cal obtained
*/
Calendar cal3 = DateUtils.toCalendar(date1);
/**
- Get time zone
- timeZone system default
- timeZone1 system default time zone
- timeZone2 set time zone
*/
Calendar calendar = new GregorianCalendar();
TimeZone timeZone = calendar.getTimeZone();
TimeZone timeZone1 = TimeZone.getDefault();
TimeZone timeZone2 = TimeZone.getTimeZone("Europe/Copenhagen");
/**
- Convert Date to Calendar with time zone
- arg0: Date type
- arg1: time zone
*/
Calendar cal4 = DateUtils.toCalendar(date1, timeZone2);
long fragment = 0;
/**
- Gets the number of milliseconds from the specified location on the specified date
- arg0: specified Date type or Calendar type
- arg1: specify where to start. int type: calendar is recommended YEAR Calendar. Constant such as month
*/
fragment = DateUtils.getFragmentInMilliseconds(date1, Calendar.MONDAY);
System.out.println("getFragmentInMilliseconds = " + fragment);
/**
- Gets the number of seconds from the specified location on the specified date
- arg0: specified Date type or Calendar type
- arg1: specify where to start. int type: calendar is recommended YEAR Calendar. Constant such as month
*/
fragment = DateUtils.getFragmentInSeconds(date1, Calendar.MONDAY);
System.out.println("getFragmentInSeconds = " + fragment);
/**
- Gets the number of minutes from the specified location on the specified date
- arg0: specified Date type or Calendar type
- arg1: specify where to start. int type: calendar is recommended YEAR Calendar. Constant such as month
*/
fragment = DateUtils.getFragmentInMinutes(date1, Calendar.MONDAY);
System.out.println("getFragmentInMinutes = " + fragment);
/**
- Gets the number of hours from the specified location on the specified date
- arg0: specified Date type or Calendar type
- arg1: specify where to start. int type: calendar is recommended YEAR Calendar. Constant such as month
*/
fragment = DateUtils.getFragmentInHours(date1, Calendar.MONDAY);
System.out.println("getFragmentInHours = " + fragment);
/**
- Gets the number of days from the specified location on the specified date
- arg0: specified Date type or Calendar type
- arg1: specify where to start. int type: calendar is recommended YEAR Calendar. Constant such as month
*/
fragment = DateUtils.getFragmentInDays(date1, Calendar.MONDAY);
System.out.println("getFragmentInDays = " + fragment);
boolean isEquals = false;
/**
- Judge whether the two times are equal above the specified position
- arg0: Time 1 Date type or Calendar type
- arg1: time2 date type or Calendar type
- arg2: Specifies the type of int at which to start the comparison: calendar is recommended YEAR Calendar. Constant such as month
*/
isEquals = DateUtils.truncatedEquals(date1, date2, Calendar.MONDAY);
System.out.println("truncatedEquals = " + isEquals);
int truncatedCompare = -1;
/**
- Compare the time difference between arg0 and arg1 at the specified location
- arg0: Time 1 Date type or Calendar type
- arg1: time2 date type or Calendar type
- arg2: Specifies the type of int at which to start the comparison: calendar is recommended YEAR Calendar. Constant such as month
*/
truncatedCompare = DateUtils.truncatedCompareTo(date1, date2, Calendar.MONDAY);
System.out.println("truncatedCompareTo = " + truncatedCompare);
Reference documents
https://www.jianshu.com/p/1886903ed14c
https://www.cnblogs.com/sharpest/p/10879564.html