[java] ArrayList <Object>를 ArrayList <String>으로 어떻게 변환 할 수 있습니까?

ArrayList<Object> list = new ArrayList<Object>();
list.add(1);
list.add("Java");
list.add(3.14);
System.out.println(list.toString());

나는 시도했다 :

ArrayList<String> list2 = (String)list; 

그러나 그것은 나에게 컴파일 오류를 주었다.



답변

이것은 실제로 문자열 목록 이 아니기 때문에 가장 쉬운 방법은이를 반복하고 각 항목을 새 문자열 목록으로 직접 변환하는 것입니다.

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

또는 아직 Java 8을 사용하지 않는 경우 :

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

또는 아직 Java 7을 사용하지 않는 경우 :

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

java.util.List구현이 아닌 인터페이스 ( 이 경우)에 대해 선언해야합니다 .


답변

그렇게하는 것은 안전하지 않습니다!
다음과 같은 경우를 상상해보십시오.

ArrayList<Object> list = new ArrayList<Object>();
list.add(new Employee("Jonh"));
list.add(new Car("BMW","M3"));
list.add(new Chocolate("Twix"));

이러한 객체 목록을 어떤 유형으로도 변환하는 것은 의미가 없습니다.


답변

더러운 방식으로하고 싶다면 이것을 시도하십시오.

@SuppressWarnings("unchecked")
public ArrayList<String> convert(ArrayList<Object> a) {
   return (ArrayList) a;
}

이점 : 여기서 모든 객체를 반복하지 않으므로 시간이 절약됩니다.

단점 : 발에 구멍이 생길 수 있습니다.


답변

구아바 사용 :

List<String> stringList=Lists.transform(list,new Function<Object,String>(){
    @Override
    public String apply(Object arg0) {
        if(arg0!=null)
            return arg0.toString();
        else
            return "null";
    }
});


답변

Java 8을 사용하여 다음을 수행 할 수 있습니다.

List<Object> list = ...;
List<String> strList = list.stream()
                           .map( Object::toString )
                           .collect( Collectors.toList() );


답변

와일드 카드를 사용하여 다음과 같이 할 수 있습니다.

ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);


답변

Guava를 사용하는 또 다른 대안이 있습니다.

List<Object> lst ...
List<String> ls = Lists.transform(lst, Functions.toStringFunction());