Convert Set to List without creating new List

前端 未结 15 918
鱼传尺愫
鱼传尺愫 2020-12-07 06:43

I am using this code to convert a Set to a List:

Map> mainMap = new HashMap<>();

for (int i         


        
15条回答
  •  轮回少年
    2020-12-07 07:11

    Java 8 provides the option of using streams and you can get a list from Set setString as:

    List stringList = setString.stream().collect(Collectors.toList());
    

    Though the internal implementation as of now provides an instance of ArrayList:

    public static 
        Collector> toList() {
            return new CollectorImpl<>((Supplier>) ArrayList::new, List::add,
                                       (left, right) -> { left.addAll(right); return left; },
                                       CH_ID);
        }
    

    but JDK does not guarantee it. As mentioned here:

    There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

    In case you want to be sure always then you can request for an instance specifically as:

    List stringArrayList = setString.stream()
                         .collect(Collectors.toCollection(ArrayList::new));
    

提交回复
热议问题