我有一个包含对象的arrayList。我需要将其解析为数组,并将所有元素作为字符串。
有什么想法吗?
假设列表中的对象具有正确重写的方法toString
,则最好使用方法Objects::toString
,该方法允许将对象安全转换为字符串。
- 使用
for-each
循环:
public static String[] convert(List<MyObject> list) {
String[] result = new String[list.size()];
int i = 0;
for (MyObject obj : list) {
result[i++] = Objects.toString(obj);
}
return result;
}
- 使用流API
public static String[] convert(List<MyObject> list) {
return list.stream()
.map(Objects::toString)
.toArray(String[]::new);
}
首先,您应该重写要转换为String的类的toString((方法,以便生成描述性字符串。(您可以使用@Data或@ToString lombok注释(
其次,您可以使用它从列表传递到数组
String[] array = objectList.stream().map(element -> element.toString()).toArray(String[]::new);