commons-lang examples

南门峰
2023-12-01

Maven Dependency

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>org.fool.commons-lang</groupId>
	<artifactId>commons-lang</artifactId>
	<version>1</version>

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

	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.0</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

 

 

find specific elements in an array

package org.fool.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

/**
 * find specific elements in an array
 */
public class ArrayIndexOfExample
{
	public static void main(String[] args)
	{
		String[] colors = { "Red", "Orange", "Yellow", "Green", "Blue",
				"Violet", "Orange", "Blue" };

		boolean containsViolet = ArrayUtils.contains(colors, "Violet");
		System.out.println("Contains Violet ? " + containsViolet);

		int indexOfYellow = ArrayUtils.indexOf(colors, "Yellow");
		System.out.println("indexOfYellow = " + indexOfYellow);

		int indexOfOrange = ArrayUtils.indexOf(colors, "Orange");
		System.out.println("indexOfOrange = " + indexOfOrange);

		int lastIndexOfOrange = ArrayUtils.lastIndexOf(colors, "Orange");
		System.out.println("lastIndexOfOrange = " + lastIndexOfOrange);
	}
}

 

reverse array elements order

package org.fool.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

/**
 * reverse array elements order
 */
public class ArrayReverseExample
{
	public static void main(String[] args)
	{
		String[] colors = { "Red", "Green", "Blue", "Cyan", "Yellow", "Magenta" };

		System.out.println(ArrayUtils.toString(colors));

		ArrayUtils.reverse(colors);
		System.out.println(ArrayUtils.toString(colors));
	}
}

 

convert an array to a Map

package org.fool.commons.lang;

import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;

/**
 * convert an array to a Map
 */
public class ArrayToMapExample
{
	public static void main(String[] args)
	{
		String[][] countries = { { "United States", "New York" },
				{ "United Kingdom", "London" }, { "Netherlands", "Amsterdam" },
				{ "Japan", "Tokyo" }, { "France", "Paris" } };

		Map<Object, Object> countryCapitals = ArrayUtils.toMap(countries);

		System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
		System.out.println("Capital of France is " + countryCapitals.get("France"));
	}
}

 

convert array of object to array of primitive

package org.fool.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

/**
 * convert array of object to array of primitive
 */
public class ObjectArrayToPrimitiveDemo
{
	public static void main(String[] args)
	{
		Integer[] integers = { new Integer(1), new Integer(2), new Integer(3),
				new Integer(5), new Integer(8), new Integer(13),
				new Integer(21), new Integer(34), new Integer(55) };

		int[] fibbos = ArrayUtils.toPrimitive(integers);
		
		System.out.println(ArrayUtils.toString(fibbos));
		System.out.println(ArrayUtils.toString(integers));
	}
}

 

convert array of primitives into array of objects

package org.fool.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

/**
 * convert array of primitives into array of objects
 */
public class PrimitiveArrayToObjectDemo
{
	public static void main(String[] args)
	{
		int numbers[] = { 1, 2, 3, 4, 5 };
		boolean bools[] = { true, false, false, true };
		float decimals[] = { 10.1f, 3.14f, 2.17f };

		Integer numbersObj[] = ArrayUtils.toObject(numbers);
		Boolean boolsObj[] = ArrayUtils.toObject(bools);
		Float decimalsObj[] = ArrayUtils.toObject(decimals);

		for (Integer i : numbersObj)
		{
			System.out.print(i + "\t");
		}

		System.out.println();

		for (Boolean b : boolsObj)
		{
			System.out.print(b + "\t");
		}

		System.out.println();

		for (Float f : decimalsObj)
		{
			System.out.print(f + "\t");
		}
	}
}

 

format date and time using DateFormatUtils class

package org.fool.commons.lang;

import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * format date and time using DateFormatUtils class
 */
public class DateFormatting
{
	public static void main(String[] args)
	{
		Date today = new Date();

		String timestamp1 = DateFormatUtils.ISO_DATE_FORMAT.format(today);
		String timestamp2 = DateFormatUtils.ISO_DATE_TIME_ZONE_FORMAT
				.format(today);
		String timestamp3 = DateFormatUtils.ISO_DATETIME_FORMAT.format(today);
		String timestamp4 = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT
				.format(today);

		String timestamp5 = DateFormatUtils.ISO_TIME_FORMAT.format(today);
		String timestamp6 = DateFormatUtils.ISO_TIME_NO_T_FORMAT.format(today);
		String timestamp7 = DateFormatUtils.ISO_TIME_NO_T_TIME_ZONE_FORMAT
				.format(today);
		String timestamp8 = DateFormatUtils.ISO_TIME_TIME_ZONE_FORMAT
				.format(today);

		String timestamp9 = DateFormatUtils.SMTP_DATETIME_FORMAT.format(today);

		System.out.println("timestamp1 = " + timestamp1);
		System.out.println("timestamp2 = " + timestamp2);
		System.out.println("timestamp3 = " + timestamp3);
		System.out.println("timestamp4 = " + timestamp4);

		System.out.println("timestamp5 = " + timestamp5);
		System.out.println("timestamp6 = " + timestamp6);
		System.out.println("timestamp7 = " + timestamp7);
		System.out.println("timestamp8 = " + timestamp8);

		System.out.println("timestamp9 = " + timestamp9);
	}
}

 

check for an empty string

package org.fool.commons.lang;

import org.apache.commons.lang3.StringUtils;

/**
 * check for an empty string
 */
public class StringUtilsDemo
{
	public static void main(String[] args)
	{
		String var1 = null;
		String var2 = "";
		String var3 = " ";
		String var4 = "		\t\t\t";
		String var5 = "Hello World";

		System.out.println("var1 is blank ? = " + StringUtils.isBlank(var1));
		System.out.println("var2 is blank ? = " + StringUtils.isBlank(var2));
		System.out.println("var3 is blank ? = " + StringUtils.isBlank(var3));
		System.out.println("var4 is blank ? = " + StringUtils.isBlank(var4));
		System.out.println("var5 is blank ? = " + StringUtils.isBlank(var5));
		
		System.out.println();
		
		System.out.println("var1 is not blank ? = " + StringUtils.isNotBlank(var1));
		System.out.println("var2 is not blank ? = " + StringUtils.isNotBlank(var2));
		System.out.println("var3 is not blank ? = " + StringUtils.isNotBlank(var3));
		System.out.println("var4 is not blank ? = " + StringUtils.isNotBlank(var4));
		System.out.println("var5 is not blank ? = " + StringUtils.isNotBlank(var5));
		
		System.out.println();
		
		System.out.println("var1 is empty? = " + StringUtils.isEmpty(var1));
        System.out.println("var2 is empty? = " + StringUtils.isEmpty(var2));
        System.out.println("var3 is empty? = " + StringUtils.isEmpty(var3));
        System.out.println("var4 is empty? = " + StringUtils.isEmpty(var4));
        System.out.println("var5 is empty? = " + StringUtils.isEmpty(var5));
 
        System.out.println();
        
        System.out.println("var1 is not empty? = " + StringUtils.isNotEmpty(var1));
        System.out.println("var2 is not empty? = " + StringUtils.isNotEmpty(var2));
        System.out.println("var3 is not empty? = " + StringUtils.isNotEmpty(var3));
        System.out.println("var4 is not empty? = " + StringUtils.isNotEmpty(var4));
        System.out.println("var5 is not empty? = " + StringUtils.isNotEmpty(var5));
	}
}

 

check if a string is empty or not

package org.fool.commons.lang;

import org.apache.commons.lang3.StringUtils;

/**
 * check if a string is empty or not
 */
public class EmptyStringCheckExample
{
	public static void main(String[] args)
	{
		String one = "";
		String two = "\t\r\n";
		String three = "     ";
		String four = null;
		String five = "four four two";

		System.out.println("Is one empty? " + StringUtils.isBlank(one));
		System.out.println("Is two empty? " + StringUtils.isBlank(two));
		System.out.println("Is three empty? " + StringUtils.isBlank(three));
		System.out.println("Is four empty? " + StringUtils.isBlank(four));
		System.out.println("Is five empty? " + StringUtils.isBlank(five));
		
		System.out.println();
		
		System.out.println("Is one not empty? " + StringUtils.isNotBlank(one));
        System.out.println("Is two not empty? " + StringUtils.isNotBlank(two));
        System.out.println("Is three not empty? " + StringUtils.isNotBlank(three));
        System.out.println("Is four not empty? " + StringUtils.isNotBlank(four));
        System.out.println("Is five not empty? " + StringUtils.isNotBlank(five));
	}
}

 

find text between two strings

package org.fool.commons.lang;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;


/**
 * find text between two strings
 */
public class NestedString
{
	public static void main(String[] args)
	{
		String helloHtml = "<html>" + "<head>"
				+ "   <title>Hello World from Java</title>" + "<body>"
				+ "Hello, today is: " + new Date() + "</body>" + "</html>";

		String title = StringUtils.substringBetween(helloHtml, "<title>",
				"</title>");
		String content = StringUtils.substringBetween(helloHtml, "<body>",
				"</body>");

		System.out.println("title = " + title);
		System.out.println("content = " + content);
	}
}

 

generate a random alpha-numeric string

package org.fool.commons.lang;

import org.apache.commons.lang3.RandomStringUtils;


/**
 * generate a random alpha-numeric string
 */
public class RandomStringUtilsDemo
{
	public static void main(String[] args)
	{
		// Creates a 64 chars length random string of number.
		String result = RandomStringUtils.random(64, false, true);
		System.out.println("random = " + result);

		// Creates a 64 chars length of random alphabetic string.
		result = RandomStringUtils.randomAlphabetic(64);
		System.out.println("random = " + result);

		// Creates a 32 chars length of random ascii string.
		result = RandomStringUtils.randomAscii(32);
		System.out.println("random = " + result);

		// Creates a 32 chars length of string from the defined array of
		// characters including numeric and alphabetic characters.
		result = RandomStringUtils.random(32, 0, 20, true, true,
				"qw32rfHIJk9iQ8Ud7h0X".toCharArray());
		System.out.println("random = " + result);
	}
}

 

reverse a string, words or sentences

package org.fool.commons.lang;

import org.apache.commons.lang3.StringUtils;

/**
 * reverse a string, words or sentences
 */
public class StringReverseExample
{
	public static void main(String[] args)
	{
		String words = "To be or not to be, that is a question !";

		// Using StringUtils.reverse we can reverse the string letter by letter.
		String reversed = StringUtils.reverse(words);

		// Now we want to reverse per word, we can use
		// StringUtils.reverseDelimited() method to do this.
		String delimitedReverse = StringUtils.reverseDelimited(words, ' ');

		System.out.println("Original: " + words);
		System.out.println("Reversed: " + reversed);
		System.out.println("Delimited Reverse: " + delimitedReverse);
	}
}

 

use Apache Commons ToStringBuilder

package org.fool.commons.lang;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * use Apache Commons ToStringBuilder
 */
public class ToStringBuilderExample
{
	private String id;
	private String firstName;
	private String lastName;

	public ToStringBuilderExample()
	{
	}

	public String getId()
	{
		return id;
	}

	public void setId(String id)
	{
		this.id = id;
	}

	public String getFirstName()
	{
		return firstName;
	}

	public void setFirstName(String firstName)
	{
		this.firstName = firstName;
	}

	public String getLastName()
	{
		return lastName;
	}

	public void setLastName(String lastName)
	{
		this.lastName = lastName;
	}

	@Override
	public String toString()
	{
		return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
				.append("id", id).append("firstName", firstName)
				.append("lastName", lastName).toString();

		// return ToStringBuilder.reflectionToString(this,
		// ToStringStyle.MULTI_LINE_STYLE);
	}

	public static void main(String[] args)
	{
		ToStringBuilderExample example = new ToStringBuilderExample();
		example.setId("1");
		example.setFirstName("Hello");
		example.setLastName("World");

		System.out.println("example = " + example);
	}
}

 

use ReflectionToStringBuilder class

package org.fool.commons.lang;

import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/**
 * use ReflectionToStringBuilder class
 */
@SuppressWarnings("unused")
public class ReflectionToString
{
	private Integer id;
	private String name;
	private String description;
	public static final String KEY = "APP-KEY";
	private transient String secretKey;

	public ReflectionToString(Integer id, String name, String description,
			String secretKey)
	{
		this.id = id;
		this.name = name;
		this.description = description;
		this.secretKey = secretKey;
	}

	@Override
	public String toString()
	{
		// Generate toString including transient and static attributes.
		return ReflectionToStringBuilder.toString(this,
				ToStringStyle.SIMPLE_STYLE, true, true);
	}

	public static void main(String[] args)
	{
		ReflectionToString demo = new ReflectionToString(1, "MANU",
				"Manchester United", "Alex");
		System.out.println("Demo = " + demo);
	}
}

 

count word occurrences in a string

package org.fool.commons.lang;

import org.apache.commons.lang3.StringUtils;

/**
 * count word occurrences in a string
 */
public class WordCountExample
{
	public static void main(String[] args)
	{
		String source = "From the download page, you can download the Java "
				+ "Tutorials for browsing offline. Or you can just download "
				+ "the examples.";

		String word = "you";

		int wordCount = StringUtils.countMatches(source, word);

		System.out.println(wordCount + " occurrences of the word '" + word
				+ "' was found in the text.");
	}
}

 

capitalize each word in a string

package org.fool.commons.lang;

import org.apache.commons.lang3.text.WordUtils;

/**
 * capitalize each word in a string
 */
public class WordCapitalize
{
	public static void main(String[] args)
	{
		// Capitalizes all the whitespace separated words in a string,
		// only the first letter of each word is capitalized.
		String str = WordUtils
				.capitalize("The quick brown fox JUMPS OVER the lazy dog.");
		System.out.println("str = " + str);

		// Capitalizes all the whitespace separated words in a string
		// and the rest string to lowercase.
		str = WordUtils
				.capitalizeFully("The quick brown fox JUMPS OVER the lazy dog.");
		System.out.println("str = " + str);
	}
}

 

use EqualsBuilder and HashCodeBuilder class

package org.fool.commons.lang;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;

/**
 * use EqualsBuilder and HashCodeBuilder class
 */
public class BookEqualsAndHashCodeExample implements Serializable
{
	private Long id;
	private String title;
	private String author;

	public BookEqualsAndHashCodeExample(Long id, String title, String author)
	{
		this.id = id;
		this.title = title;
		this.author = author;
	}

	@Override
	public int hashCode()
	{
		return new HashCodeBuilder().append(id).append(title).append(author)
				.toHashCode();

		// Or even use the simplest method using reflection below.
		// return HashCodeBuilder.reflectionHashCode(this);
	}

	@Override
	public boolean equals(Object obj)
	{
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;

		BookEqualsAndHashCodeExample other = (BookEqualsAndHashCodeExample) obj;

		return new EqualsBuilder().append(this.id, other.id)
				.append(this.title, other.title)
				.append(this.author, other.author).isEquals();

		// You can also use reflection of the EqualsBuilder class.
		// return EqualsBuilder.reflectionEquals(this, other);
	}

	public static void main(String[] args)
	{
		Set<Object> set = new HashSet<>();

		set.add(new BookEqualsAndHashCodeExample(1L, "HashCode", "Hello"));
		set.add(new BookEqualsAndHashCodeExample(1L, "HashCode", "Hello"));

		System.out.println(set.size());
	}
}

 

use CompareToBuilder class

package org.fool.commons.lang;

import org.apache.commons.lang3.builder.CompareToBuilder;

/**
 * use CompareToBuilder class
 */
public class CompareToExample
{
	public static void main(String[] args)
	{
		Fruit orange = new Fruit("Orange", "Orange");
		Fruit watermelon = new Fruit("Watermelon", "Red");

		if (orange.compareTo(watermelon) == 0)
		{
			System.out
					.println(orange.getName() + " == " + watermelon.getName());
		}
		else
		{
			System.out
					.println(orange.getName() + " != " + watermelon.getName());
		}
	}
}

class Fruit
{
	private String name;
	private String colour;

	public Fruit(String name, String colour)
	{
		this.name = name;
		this.colour = colour;
	}

	public String getName()
	{
		return name;
	}

	/*
	 * Generating compareTo() method using CompareToBuilder class. For other
	 * alternative way we can also use the reflectionCompare() method to
	 * implement the compareTo() method.
	 */
	public int compareTo(Object o)
	{
		Fruit f = (Fruit) o;
		return new CompareToBuilder().append(this.name, f.name)
				.append(this.colour, f.colour).toComparison();

		// return CompareToBuilder.reflectionCompare(this, f);
	}
}

 

 

 

 

 

 类似资料: