目录 待去重列表 HashSet去重(不保证顺序) TreeSet去重(不保证顺序) LinkedHashSet去重(保证顺序) 遍历List去重(保证顺序) Java8中Stream流处理(保证顺序) 参考文章
待去重列表
List < String > list = new ArrayList < > ( ) ;
list. add ( "Tom" ) ;
list. add ( "Jack" ) ;
list. add ( "Steve" ) ;
list. add ( "Tom" ) ; System . out. println ( list) ;
HashSet去重(不保证顺序)
Set < String > set = new HashSet < > ( list) ;
List < String > newList = new ArrayList < > ( set) ; System . out. println ( newList) ;
TreeSet去重(不保证顺序)
Set < String > set = new TreeSet < > ( list) ;
List < String > newList = new ArrayList < > ( set) ; System . out. println ( newList) ;
LinkedHashSet去重(保证顺序)
Set < String > set = new LinkedHashSet < > ( list) ;
List < String > newList = new ArrayList < > ( set) ; System . out. println ( newList) ;
遍历List去重(保证顺序)
List < String > newList = new ArrayList < > ( ) ;
for ( String value : list) { if ( ! newList. contains ( value) ) { newList. add ( value) ; }
} System . out. println ( newList) ;
Java8中Stream流处理(保证顺序)
List < String > newList = list. stream ( ) . distinct ( ) . collect ( Collectors . toList ( ) ) ; System . out. println ( newList) ;
参考文章
List 去重的 6 种方法,这个方法最完美!