How to make an accept List method that contains objects of any data type

My goal is to check the type of messages and then convert them accordingly 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)); } } } 
+5
source share
4 answers

You can simply pass a list of objects β€” you don’t even need if / else, since you can always call "toString ()" or "String.valueOf" in the message object:

 public void addMessages(List<Object> messages) { if (!CollectionUtils.isEmpty(messages)) { for (Object message : messages) { this.messages.add(String.valueOf(message)); } } } 

On the other hand: potential problems can arise due to the presence of zero elements in the message list, so you can check this in your loop. Other potential problems:

  • this.messages is not initialized and adding messages raises a NullPointerException
  • if it is a single point method (e.g. spring service) that should be avoided
+3
source
 public void addMessages(List<Object> messages) { 

This is sufficient if messages contains all types of objects.

+2
source

You can achieve this with Java Generics.

The Messages object, initialized in the main method below, will accept a list of objects of any type. You can also initialize the Messages object with a specific type.

 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 **/); } } 
+1
source

This is just an improvement on nutfox's answers.

 public void addMessages(List<?> messages) { List<String> collect = messages.stream().map(i -> String.valueOf(i)).collect(Collectors.toList()); this.messages.addAll(collect); } 
0
source

All Articles