Java Frequently Used Utillity Methods


Objects.requireNonNull(key, message)
Objects.equals(a,b) - null safe
StringBuilder
.charAt(i) 
.setCharAt(int, char)
.setLength(0)/setLength(len-1)
- O(1) if decrease the length
.reverse()
.insert(offset,value)
.delete(start,end)
.deleteCharAt(i)


Arrays.equals(a1,a2)
.fill(long[] a, long val)
fill(long[] a, int fromIndex, int toIndex, long val)

To fill multiple dimension arrays:
int[][] target = new int[2][4];
int [] temp = new int[4];
Arrays.fill(temp, -1);

Arrays.fill(target, temp);

Collection
List
E remove(int index);
boolean remove(Object o);

ListIterator
next/hasNext/nextIndex, previous/hasPrevious/previousIndex, 
add/remove/set

ArrayList.subList
remove elements from startIndex to endIndex
list1.subList(startIndexendIndex).clear();
Don't update original list while still need the subList.

Arrays.asList(T…a) returns a Subclass of AbstractList that doesn’t implement the add or remove method - it throws UnsupportedOperationException.

JDK 8
map.putIfAbsent(sum, i);
Instead of:
if (!map.containsKey(sum)) {
    map.put(sum, i);
}

map.getOrDefault(key, defaultValue)
computeIfAbsent
computeIfPresent

Lambda
iterable.forEach(x -> x.setXXX(null));
list.removeIf(s -> s.length() == 0);

Stream
list.replaceAll(s -> s.toUpperCase());
list.sort((x, y) -> x.length() – y.length());
logger.finest(() -> complexMsg());
lineCount = Files.lines(path).count();

Collectors
stream().collect(Collectors.groupingBy(xxx));
mapStream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Math:
Math.xxxExact - throws exception if overflow
addExact/subtractExact...
Base64

SecureRandom.getInstanceStrong()

Enum
SomeEnum someEnum = Enum.valueOf(SomeEnum.class, value);

// Need escape ': ''
MessageFormat.format

Initilaize 2-d array
int[][] target = new int[2][4];
int [] temp = new int[4];
Arrays.fill(temp, -1);
Arrays.fill(target, temp);

Get the inputstream from classpath:
ClassLoader.getResourceAsStream()

Guava
Preconditions
MoreObjects
firstNonNull(@Nullable T first, @Nullable T second)
joiner = Joiner.on("; ").skipNulls();
splitter = Splitter.on(',').trimResults().omitEmptyStrings();

ComparisonChain.start().compare(this.aString, that.aString)....compare(this.anEnum, that.anEnum, Ordering.natural().nullsLast()).result();

Ordering<String> ordering = = Ordering.nullsFirst().reverse();

Collections.sort(names, ordering);
Map<String, String> paramMap = Splitter.on("&").withKeyValueSeparator("=").split(params);
Joiner.on("&").withKeyValueSeparator("=").join(paramMap);

CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, tableName);

HtmlEscapers.htmlEscaper().escape(str)
UrlEscapers.urlFormParameterEscaper()/urlFragmentEscaper()/urlPathSegmentEscaper()/urlFormParameterEscaper().

Files.hash(file, Hashing.md5());
RateLimiter

Solr Commons
DateUtil.parseDate(dateString)
DateUtil.getThreadLocalDateFormat().format(date)

Top 16 Java Utility Classes
Apache Commons
StringUtils
CollectionUtils
ReflectionToStringBuilder.toString(this)

org.apache.commons.lang.SerializationUtils
clone
serialize
deserialize

ObjectUtils
firstNonNull(T... values)
defaultIfNull(final T object, final T defaultValue)

ArrayUtils.contains(arr,targetValue)


Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)