Merge ListUtil into StringUtil; refactor HelpSyntaxHelper + create test

The HelpSyntaxHelper had suppressed warnings for string concatenation within StringBuilder - the point of the StringBuilder is that it is faster when you use it to concatenate many elements. If you still use string concatenation with + within these calls it beats the purpose.
This commit is contained in:
ljacqu
2015-11-21 11:57:04 +01:00
parent a3f24bcb9a
commit b3d0a71dec
6 changed files with 159 additions and 91 deletions
@@ -1,58 +0,0 @@
package fr.xephi.authme.util;
import java.util.ArrayList;
import java.util.List;
/**
*/
public class ListUtils {
/**
* Implode a list of elements into a single string, with a specified separator.
*
* @param elements The elements to implode.
* @param separator The separator to use.
*
* @return The result string. */
public static String implode(List<String> elements, String separator) {
// Create a string builder
StringBuilder sb = new StringBuilder();
// Append each element
for(String element : elements) {
// Make sure the element isn't empty
if(element.trim().length() == 0)
continue;
// Prefix the separator if it isn't the first element
if(sb.length() > 0)
sb.append(separator);
// Append the element
sb.append(element);
}
// Return the result
return sb.toString();
}
/**
* Implode two elements into a single string, with a specified separator.
*
* @param element The first element to implode.
* @param otherElement The second element to implode.
* @param separator The separator to use.
*
* @return The result string. */
public static String implode(String element, String otherElement, String separator) {
// Combine the lists
List<String> combined = new ArrayList<>();
combined.add(element);
combined.add(otherElement);
// Implode and return the result
return implode(combined, separator);
}
}
@@ -49,4 +49,39 @@ public class StringUtils {
return false;
}
/**
* Null-safe method for checking whether a string is empty. Note that the string
* is trimmed, so this method also considers a string with whitespace as empty.
*
* @param str the string to verify
*
* @return true if the string is empty, false otherwise
*/
public static boolean isEmpty(String str) {
return str == null || str.trim().isEmpty();
}
/**
* Joins a list of elements into a single string with the specified delimiter.
*
* @param delimiter the delimiter to use
* @param elements the elements to join
*
* @return a new String that is composed of the elements separated by the delimiter
*/
public static String join(String delimiter, Iterable<String> elements) {
StringBuilder sb = new StringBuilder();
for (String element : elements) {
if (!isEmpty(element)) {
// Add the separator if it isn't the first element
if (sb.length() > 0) {
sb.append(delimiter);
}
sb.append(element);
}
}
return sb.toString();
}
}