我有一个可能包含或不包含重复值的列表:
如果有重复的“ ABC”值(此问题仅是ABC)
List myList = {“ ABC”,“ EFG”,“ IJK”,“ ABC”,“ ABC”},
我想将列表分为两个列表以最终得到:
列出重复值= {“ ABC”};
列出nonDuplicatedValues = {“ EFG”,“ IJK”};
同样,如果列表中不止一个“ ABC”,它将返回相同的列表
我到目前为止所做的:
void generateList(List<String> duplicatedValues, List<String> nonDuplicatedValues){
List<String> myList=List.of("ABC","EFG","IJK","ABC","ABC");
Optional<String> duplicatedValue = myList.stream().filter(isDuplicated -> Collections.frequency(myList, "ABC") > 1).findFirst();
if(duplicatedValue.isPresent())
{
duplicatedValues.addAll(List.of(duplicatedValue.get()));
nonDuplicatedValues.addAll(myList.stream().filter(string->string.equals("ABC")).collect(Collectors.toList()));
}
else
{
nonDuplicatedValues.addAll(myList);
}
}
是否存在仅使用myList流的更有效方法?
您可以两次播放列表,如下所示:
public static void main(String[] args) {
// example list with values
List<String> myList = new ArrayList<>();
myList.add("ABC");
myList.add("EFG");
myList.add("IJK");
myList.add("ABC");
myList.add("ABC");
// print the original list once
System.out.println("Source List: " + String.join(", ", myList));
// stream the list
List<String> distinctValues = myList.stream()
// and collect all the values that occur exactly once
.filter(i -> Collections.frequency(myList, i) == 1)
.collect(Collectors.toList());
// print the result
System.out.println("Distinct Values: " + String.join(", ", distinctValues));
// stream the list again
List<String> duplicates = myList.stream()
// and collect all the values that occur more than once
.filter(i -> Collections.frequency(myList, i) > 1)
// and don't allow duplicate entries
.distinct()
.collect(Collectors.toList());
// then print the result
System.out.println("Duplicates: " + String.join(", ", duplicates));
}
此示例的输出是
Source List: ABC, EFG, IJK, ABC, ABC
Distinct Values: EFG, IJK
Duplicates: ABC