[英]How to remove duplicates ArrayList from an ArrayList of ArrayList
[英]How to delete duplicates from an arraylist
我正在嘗試從 arraylist 中刪除重復項:
public static List<List<String>> bigList = new ArrayList<>();
for (int i = 0; i < bigList.size(); i++) {
bigList.get(i).stream()
.map(str -> new LinkedHashSet<>(Arrays.asList(str.split(","))))
.distinct()
.map(set -> set.stream().collect(Collectors.joining(",")))
.collect(Collectors.toList());
}
}
執行代碼時,我的列表中仍然存在重復項。 我想從 bigList 和 bigList.get(i) 中刪除重復項。
您的代碼每次通過for
循環創建一個新列表。 但新列表立即丟失,前往垃圾收集。 您忽略了捕獲對該新創建列表的引用。
因此,解決方案是:用新列表替換作為元素存儲在外部列表中的舊列表。 用bigList.set( i, … )
包裹您的 stream 行。
public static List< List< String > > bigList = new ArrayList<>(); // A list of lists of strings.
…
for (int i = 0; i < bigList.size(); i++) {
bigList.set(
i , // Index of outer list, where the new list should go.
bigList
.get(i)
.stream()
.map( str -> new LinkedHashSet<>( Arrays.asList( str.split( "," ) ) ) )
.distinct()
.map( set -> set.stream().collect( Collectors.joining( "," ) ) )
.collect( Collectors.toList() ) // Produce a new list. Stored in place of the old list.
) ;
}
為清楚起見,將代碼分成單獨的行。
public static List< List< String > > bigList = new ArrayList<>(); // A list of lists of strings.
…
for (int i = 0; i < bigList.size(); i++) {
List< String > oldList = bigList.get( i ) ;
List< String > newList =
oldList
.stream()
.map( str -> new LinkedHashSet<>( Arrays.asList( str.split( "," ) ) ) )
.distinct()
.map( set -> set.stream().collect( Collectors.joining( "," ) ) )
.collect( Collectors.toList() ) // Produce a new list. Stored in place of the old list.
) ;
bigList.set( i , newList ) ; // Replace the old list with the newly-created list.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.