How can I convert ArrayList<Object> to ArrayList?

后端 未结 11 794
-上瘾入骨i
-上瘾入骨i 2020-11-28 06:31
ArrayList list = new ArrayList();
list.add(1);
list.add(\"Java\");
list.add(3.14);
System.out.println(list.toString());


11条回答
  •  难免孤独
    2020-11-28 07:14

    Since this is actually not a list of strings, the easiest way is to loop over it and convert each item into a new list of strings yourself:

    List strings = list.stream()
       .map(object -> Objects.toString(object, null))
       .collect(Collectors.toList());
    

    Or when you're not on Java 8 yet:

    List strings = new ArrayList<>(list.size());
    for (Object object : list) {
        strings.add(Objects.toString(object, null));
    }
    

    Or when you're not on Java 7 yet:

    List strings = new ArrayList(list.size());
    for (Object object : list) {
        strings.add(object != null ? object.toString() : null);
    }
    

    Note that you should be declaring against the interface (java.util.List in this case), not the implementation.

提交回复
热议问题