Created
January 13, 2017 17:23
-
-
Save tasdemirbahadir/24a13440c01c148d8e43d336add49c5a to your computer and use it in GitHub Desktop.
Java Object Collection To String With Delimiter and Optional Field Usage For Object Values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Convert list to string with delimiter | |
* @param <T> class of the collection | |
* @param values Given long values | |
* @param classTypeParam Pass class type to get fields, do not set null | |
* @param fieldName Name of the field of the object to get value of | |
* @param delimiter Given delimiter | |
* @return ({1L,3L,5L} + Long.class + null + ",") --> ("1,3,5") | |
* ({{id:1},{id:2},{id:3}} + ObjectClass.class + "id" + ",") --> ("1,2,3") | |
*/ | |
public static <T> String collectionToString(Collection<T> values, Class<T> classTypeParam, String fieldName, String delimiter) { | |
if (values == null || values.size() == 0) { | |
return ""; | |
} else { | |
int fieldIndex = 0; | |
boolean useField = !StringUtils.isNullOrEmpty(fieldName); | |
Field[] fields = classTypeParam.getDeclaredFields(); | |
if (useField) { | |
while (!fields[fieldIndex].getName().equals(fieldName)) | |
fieldIndex++; | |
} | |
StringBuilder sb = new StringBuilder(); | |
int index = 0; | |
for (T value: values) { | |
if (useField) { | |
try { | |
sb.append(fields[fieldIndex].get(fieldName)); | |
} catch (IllegalArgumentException | IllegalAccessException e) { | |
sb.append(value); | |
} | |
} else { | |
sb.append(value); | |
} | |
if (index < values.size() - 1) { | |
sb.append(delimiter); | |
} | |
index++; | |
} | |
return sb.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment