Reputation: 2480
My goal is to check the type of messages
and then accordingly convert them to Strings and add them. How can I achieve this?
public void addMessages(List<?> messages) {
if (messages != null) {
if (messages instanceof String) {
for (String message : messages) {
this.messages.add(message);
}
}
}
else {
for (Object message:messages) {
this.messages.add(String.valueOf(message));
}
}
}
Upvotes: 7
Views: 6459
Reputation: 3240
This is just an enhancement over the answers by nutfox.
public void addMessages(List<?> messages) {
List<String> collect = messages.stream().map(i -> String.valueOf(i)).collect(Collectors.toList());
this.messages.addAll(collect);
}
Upvotes: 2
Reputation: 1874
You can achieve that with "Java Generics".
The Messages
object initialized in the main method below will accept the list of objects of any type. You can initialize Messages
object with a specific type as well.
public class Messages<T> {
private List<T> messages = new ArrayList<T>();
public void addMessages(List<T> messages) {
for (T message : messages) {
// Use String.valueOf or message.toString()
// if you would like to convert the objects to String.
}
}
public static void main(String[] args) {
Messages<Object> msg = new Messages<Object>();
msg.addMessages(/** Your List of objects of any type **/);
}
}
Upvotes: 1
Reputation: 484
You can just pass in a List of Objects - you don't even need the if/else since you can just always call "toString()" or "String.valueOf" on the message object:
public void addMessages(List<Object> messages) {
if (!CollectionUtils.isEmpty(messages)) {
for (Object message : messages) {
this.messages.add(String.valueOf(message));
}
}
}
On a side note: Potential problems could arise from having null elements in the messages list - so you might want to check for that in your loop. Other potential pitfalls are:
NullPointerException
Upvotes: 3
Reputation: 121998
public void addMessages(List<Object> messages) {
That is just enough where messages
hold all type of Objects.
Upvotes: 1