Copying sets Java

后端 未结 5 947
清歌不尽
清歌不尽 2021-01-31 01:19

Is there a way to copy a TreeSet? That is, is it possible to go

Set  itemList;
Set  tempList;

tempList = itemList;
<         


        
5条回答
  •  不思量自难忘°
    2021-01-31 01:35

    With Java 8 you can use stream and collect to copy the items:

    Set newSet = oldSet.stream().collect(Collectors.toSet());
    

    Or you can collect to an ImmutableSet (if you know that the set should not change):

    Set newSet = oldSet.stream().collect(ImmutableSet.toImmutableSet());
    

提交回复
热议问题