1. How to compare equals for two List:
1> Writing boiler plate code
2> Use org.apache.commons.collections.ListUtils.isEqualList()
Benefit: Help us handle boiler plate code for null check.
public static boolean isEqualList(final Collection list1, final Collection list2) { if (list1 == list2) { return true; } if (list1 == null || list2 == null || list1.size() != list2.size()) { return false; } Iterator it1 = list1.iterator(); Iterator it2 = list2.iterator(); Object obj1 = null; Object obj2 = null; while (it1.hasNext() && it2.hasNext()) { obj1 = it1.next(); obj2 = it2.next(); if (!(obj1 == null ? obj2 == null : obj1.equals(obj2))) { return false; } } return !(it1.hasNext() || it2.hasNext()); }
Set Operations:
1. How to compare equals for two Sets?
Use org.apache.commons.collections.SetUtils.isEqualSet():
Benefit: Help us handle boiler plate code for null check.
public static boolean isEqualSet(final Collection set1, final Collection set2) { if (set1 == set2) { return true; } if (set1 == null || set2 == null || set1.size() != set2.size()) { return false; } return set1.containsAll(set2); }
2. How to operate subtraction between two Sets?
Use com.google.common.collect.Sets.difference()
@Test public void subtractTest() { Set<String> strSet1 = Sets.newHashSet("A", "B", "C", "D"); Set<String> strSet2 = Sets.newHashSet("D", "M", "O", "G"); Set<String> strSet1SubtractStrSet2 = Sets.difference(strSet1, strSet2); assertTrue(SetUtils.isEqualSet(Sets.newHashSet("A", "B", "C"), strSet1SubtractStrSet2)); Set<String> strSet2SubtractStrSet1 = Sets.difference(strSet2, strSet1); assertTrue(SetUtils.isEqualSet(Sets.newHashSet("M", "O", "G"), strSet2SubtractStrSet1)); }
3. How to operate union between two Sets?
Use com.google.common.collect.Sets.union()
4. How to operate intersection between two Sets?
Use com.google.common.collect.Sets.intersection()
5. How to operate symmetric difference between two Sets?
Use com.google.common.collect.Sets.symmetricDifference()
@Test public void symmetricDifferenceTest() { Set<String> strSet1 = Sets.newHashSet("A", "B", "C", "D"); Set<String> strSet2 = Sets.newHashSet("D", "M", "O", "G"); Set<String> symmetricDifference = Sets.symmetricDifference(strSet1, strSet2); assertTrue(SetUtils.isEqualSet( Sets.newHashSet("A", "B", "C", "M", "O", "G"), symmetricDifference)); }
String Operation:
1> Strings.isNullOrEmpty()
2> Strings.nullToEmpty()
3> How to swap case for a String?
import static org.junit.Assert.assertEquals; import org.apache.commons.lang3.StringUtils; import org.junit.Test; public class StringTest { @Test public void swapCaseTest() { String str = "Hello"; assertEquals("hELLO", StringUtils.swapCase(str)); } }StringUtils.swapCase source code:
public static String swapCase(final String str) { if (StringUtils.isEmpty(str)) { return str; } final char[] buffer = str.toCharArray(); for (int i = 0; i < buffer.length; i++) { final char ch = buffer[i]; if (Character.isUpperCase(ch)) { buffer[i] = Character.toLowerCase(ch); } else if (Character.isTitleCase(ch)) { buffer[i] = Character.toLowerCase(ch); } else if (Character.isLowerCase(ch)) { buffer[i] = Character.toUpperCase(ch); } } return new String(buffer); }
4> How to remove all spaces in a String?
@Test public void removeSpaceTest() { String str = "Hello world, I am Davy"; String removedStr = StringUtils.remove(str, ' '); // Find space from target String char by char assertEquals("Helloworld,IamDavy", removedStr); removedStr = str.replaceAll("\\s", ""); // Find space from target String by regex assertEquals("Helloworld,IamDavy", removedStr); removedStr = str.replaceAll("\\s+", ""); // Find space from target String by regex assertEquals("Helloworld,IamDavy", removedStr); }
StringUtils.remove source code:
public static String remove(final String str, final char remove) { if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { return str; } final char[] chars = str.toCharArray(); int pos = 0; for (int i = 0; i < chars.length; i++) { if (chars[i] != remove) { chars[pos++] = chars[i]; } } return new String(chars, 0, pos); }
5> How to reverse String?
@Test public void reverseStringTest() { String str = "Hello world, I am Davy"; String reversedStr = StringUtils.reverse(str); assertEquals("yvaD ma I ,dlrow olleH", reversedStr); reversedStr = new StringBuilder(str).reverse().toString(); assertEquals("yvaD ma I ,dlrow olleH", reversedStr); // Or we can use Stack<Character> to reverse a String Stack<Character> stack = new Stack<Character>(); for (char c : str.toCharArray()) { stack.push(c); } StringBuilder sb = new StringBuilder(); while (!stack.empty()) { sb.append(stack.pop()); } reversedStr = sb.toString(); assertEquals("yvaD ma I ,dlrow olleH", reversedStr); }StringUtils.reverse source code:
public static String reverse(final String str) { if (str == null) { return null; } return new StringBuilder(str).reverse().toString(); }
Char Operation:
1> How to recognize a char is upper case or lower case?
@Test public void caseTest() { char c = 'A'; assertTrue(Character.isUpperCase(c)); c = 'a'; assertTrue(Character.isLowerCase(c)); c = '0'; assertFalse(Character.isUpperCase(c)); assertFalse(Character.isLowerCase(c)); }
2> How to swap case for char?
@Test public void swapCaseTest() { char c = 'A'; assertEquals('a', Character.toLowerCase(c)); c = 'a'; assertEquals('A', Character.toUpperCase(c)); c = '0'; assertEquals('0', Character.toUpperCase(c)); assertEquals('0', Character.toLowerCase(c)); }
File Operation:
1> How to create temp file simply? -Use File.createTempFile();
public static File createTempFile(String prefix, String suffix, File directory); import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.junit.Test; public class FileTest { @Test public void createTempFileTest() throws IOException { File tmpFile = File.createTempFile("test", ".tmp"); File srcFile = new File("src/main/resources/spring.xml"); FileUtils.copyFile(srcFile, tmpFile, false); } } // The tmpFile would be C:/Users/userID/AppData/Local/Temp/test3900920229769745162.tmp
2> How to copy file simply? -Use FileUtils.copyFile();
3> How to close I/O stream? -Use IOUtils.closeQuitely();
Java Date Format:
1> java.text.SimpleDateFormat is not thread safe, use org.apache.commons.lang.time.FastDateFormat instead.
2> "yyyyMMdd" is Year-Month-Day, "MM" is "Month" and "mm" is "Minutes".
Java Reflect:
1> How to know if a class is primitive type or not?
Class<?> clazz = Integer.class; Class<?> clazz2 = int.class; if (clazz.isPrimitive()) { System.out.println("PRIMITIVE"); }else{ System.out.println("NON_PRIMITIVE"); }
Reference Links:
1) http://stackoverflow.com/questions/9698652/subtraction-of-two-sets-in-java
2) http://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java