Fix Utils.nonEmptyAndNullJoin

When using the index here, it the index needs to be decremented once an element is removed. To cirecumvent this, the native Collections.removeIf() method is used.
This commit is contained in:
TobiGr 2021-02-21 12:51:47 +01:00
parent b9e8ee8450
commit 70814dcfef
2 changed files with 4 additions and 8 deletions

View File

@ -274,14 +274,9 @@ public class Utils {
/** /**
* Concatenate all non-null, non-empty and strings which are not equal to <code>"null"</code>. * Concatenate all non-null, non-empty and strings which are not equal to <code>"null"</code>.
*/ */
public static String nonEmptyAndNullJoin(final String delimiter, final String[] elements) { public static String nonEmptyAndNullJoin(final CharSequence delimiter, final String[] elements) {
final List<String> list = Arrays.asList(elements); final List<String> list = new java.util.ArrayList<>(Arrays.asList(elements));
for (int i = list.size() - 1; i >= 0; i--) { list.removeIf(s -> isNullOrEmpty(s) || s.equals("null"));
if (isNullOrEmpty(list.get(i)) || list.get(i).equals("null")) {
list.remove(i);
}
}
return join(delimiter, list); return join(delimiter, list);
} }
} }

View File

@ -20,6 +20,7 @@ public class UtilsTest {
@Test @Test
public void testJoin() { public void testJoin() {
assertEquals("some,random,stuff", Utils.join(",", Arrays.asList("some", "random", "stuff"))); assertEquals("some,random,stuff", Utils.join(",", Arrays.asList("some", "random", "stuff")));
assertEquals("some,random,not-null,stuff", Utils.nonEmptyAndNullJoin(",", new String[]{"some", "null", "random", "", "not-null", null, "stuff"}));
} }
@Test @Test