`
DavyJones2010
  • 浏览: 153760 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java SE: Tips

阅读更多

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

 

分享到:
评论

相关推荐

    Java SE 8 Programmer I Study Guide: Exam 1Z0-808

    Title: OCA: Oracle Certified Associate Java SE 8 Programmer I Study Guide: Exam 1Z0-808 Author: Jeanne Boyarsky, Scott Selikoff Length: 432 pages Edition: 1 Language: English Publisher: Sybex ...

    1Z0-811 Exam Guide to Have a Cakewalk in Oracle Java SE Certific

    - **Self-Study Tips:** If opting for self-study, ensure that you cover each topic at least 2-3 times to solidify your understanding. Utilize resources like online forums, practice tests, and ...

    Java: A Beginner's Guide 5th Edition

    Fully updated to cover Java Platform, Standard Edition 7 (Java SE 7), Java: A Beginner's Guide, Fifth Edition starts with the basics, such as how to compile and run a Java program, and then discusses...

    java tips everyday课程内容预览

    javaTipsEveryday来自http://javatipseveryday.com - The Brand New Java Training Course的课程内容一览,大体包括java SE,java开发框架等等 1.如何设计Java编程职业。 2.成功建立职业生涯的秘密策略。 3.像专业...

    330-Java-Tips.rar_LOT

    7. **Java标准库**:Java SE库提供了大量预定义类和方法,如Arrays、Collections、Date/Time API等,掌握这些可以帮助编写更高效、简洁的代码。 8. **设计模式**:文档可能会涵盖常见的设计模式,如工厂模式、单例...

    2014秋季Java程序设计期末考试试卷(A卷).doc

    * Java 程序的开发工具标准版本:Java SE 二、Java 变量和数据类型 * Java 变量的命名习惯:驼峰命名法、字母数字下划线组成 * Java 数据类型:基本类型(int、float、char 等)、引用类型(数组、对象) * 数据...

    java.核心技术.第八版 卷1

    Volume I is designed to quickly bring you up to speed on what’s new in Java SE 6 and to help you make the transition as efficiently as possible, whether you’re upgrading from an earlier version of ...

    Tricks and Tips With NIO Using the Grizzly Framework

    Java NIO (New I/O) 是Java SE 1.4版本引入的一个新特性,它提供了非阻塞I/O操作的能力,从而使得程序可以处理更多的并发连接。Java NIO主要由以下三个核心组件构成: - **ByteBuffer**: 用于存储数据的缓冲区。 - ...

    SCJP 065 题库

    SCJP(Sun Certified Programmer for the Java 2 Platform, Standard Edition 6)是Oracle公司认证的Java程序员考试,针对的是Java SE 6版本。这个"SCJP 065 题库"包含了针对该考试的一些学习资料和练习题目,帮助...

    在哪里可以获取视频或在Java编码上进行项目的一些技巧? 请提供一些有关此查询的详细信息。

    - Java SE Documentation (https://docs.oracle.com/en/java/javase/17/) 提供了API参考和其他技术信息。 3. **开源社区**: - **GitHub**: 可以找到各种Java项目的源代码,通过阅读和参与开源项目,可以学习实际...

    building restful web services with spring 5 2e

    Building RESTful Web Services with Spring 5 – Second Edition: Leverage the power of Spring 5.0, Java SE 9, and Spring Boot 2.0 Find out how to implement the REST architecture to build resilient ...

    达内SCJP考试模拟试题 (310-055)

    这个考试主要针对初级到中级的Java程序员,测试他们对Java SE平台的基本理解和编程能力。"达内SCJP考试模拟试题 (310-055)"是一套专门为准备SCJP考试而设计的练习资源。 这套模拟试题分为多个模块,涵盖了Java的...

    Flex Builder Plug-in and Adobe

    Once downloaded, unpack the Eclipse archive (installation is not required) and ensure that you have a JRE (Java SE Runtime Environment) installed. If not, download it from the Oracle website. #### ...

    JDK 1.8 安装配置教程(win7 64bit )

    下载地址是 Java SE Development Kit 8 Downloads。需要注意的是,在选择版本时,需要根据 Eclipse 的安装版本来选择 JDK 的版本。如果 Eclipse 安装的是 32 位的,则需要下载 Windows x86(32 位)的 JDK;如果 ...

    Geoserver用户手册

    6.3 Java Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159 6.4 GML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ...

    UE(官方下载)

    This power tip provides an explanation as well as some tips to get the most out of temp files. Backup and Restore Settings One of the staples of UltraEdit (and UEStudio) is its highly configurable ...

Global site tag (gtag.js) - Google Analytics