antoine.lange antoine.lange - 4 months ago 13
Java Question

Concatenate object values regarding name of fields in alphabetical order

I'm looking for a method to concatenate object values regarding name of fields in alphabetical order.

Example:

public Class Request {
private String number;
private String amount;
private String currency;
}

Request request = new Request();
request.setNumber("tata");
request.setCurrency("toto");


With this, my method should return
tototata
.

Method must be generic:

public static String concatenate(Object object) { ...}


null
values must not be concatenated.

I already checked out Apache Commons BeanUtils and Java 8 streams, but found nothing nice.

Answer

You may write this by iterating over all declared fields in the given object.

public static String concatenate(Object object) {
    return Arrays.stream(object.getClass().getDeclaredFields())
                 .filter(f -> f.getType() == String.class)
                 .sorted(Comparator.comparing(Field::getName))
                 .map(f -> {
                      try { return (String)f.get(object); }
                      catch (IllegalAccessException e) { return null; }
                  })
                 .filter(Objects::nonNull)
                 .collect(Collectors.joining());
}
Comments