我需要在不使用嵌套 for 回圈的情況下檢查串列 A 中存在的物件是否存在于串列 B 中,因為如果串列的大小很大,則需要太多時間。
這是我的代碼:
for(Person el : persons)
{
for(Client in : clients)
{
if(el.getIdentifier() == in.getTire().getIdentifier())
{
exists=true;
break;
}
}
}
如何在不使用回圈和中斷的情況下獲得相同的結果?
uj5u.com熱心網友回復:
也許你可以這樣做
Set<String> identifierSet = new HashSet<>();
for (Person el : persons) {
identifierSet.add(el.getIdentifier());
}
for (Client in : clients) {
if (identifierSet.contains(in.getTire().getIdentifier())) {
exists = true;
break;
}
}
uj5u.com熱心網友回復:
您可以通過使用更適合快速查找的資料結構來提高性能。如果您將客戶端存盤在 HashMap 中,其中鍵是識別符號,值是客戶端物件,那么您的代碼將變為:
for(Person el : persons)
{
if (clients.containsKey(el.getIdentifier()) {
exists=true;
}
}
現在你只有一個回圈,在 hashmap 中查找的成本是 O(1)。
uj5u.com熱心網友回復:
這會將代碼的復雜度從 O(NxM) 更改為 O(N M):
Set<Integer> personIds = persons.stream()
.map(e -> e.getIdentifier())
.collect(Collectors.toCollection(HashSet::new));
boolean exists = clients.stream().anyMatch(
c -> personIds.contains(c.getTire().getIdentifier()));
uj5u.com熱心網友回復:
如anyMatch提及,可以提供基于流API下述溶液(假定識別符號的型別是String):
// prepare set of identifiers in clients
Set<String> clientIds = clients
.stream() // Stream<Client>
.map(in -> in.getTire().getIdentifier()) // Stream<String> client ids
.collect(Collectors.toSet());
boolean anyPersonIsClient = persons
.stream() // Stream<Person>
.map(Person::getIdentifier) // Stream<String> person identifiers
.anyMatch(clientIds::contains);
boolean allPersonsAreClient = persons
.stream() // Stream<Person>
.map(Person::getIdentifier) // Stream<String> identifiers
.allMatch(clientIds::contains);
uj5u.com熱心網友回復:
經典的怎么樣:
contains(Object o) //Returns true if this list contains the specified element.
所以你可以只做回圈:
for(Person el : persons)
{
if(clients.contains(el.getIdentifier()))
{
exists=true;
break;
}
}
但是查看您的代碼,并根據您的目標,您可以使用:
containsAll(Collection c)
// Returns true if this list contains all of the elements of the specified collection.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/318003.html
上一篇:根據匿名物件訪問限制器的實作方法
下一篇:將方法作為變數分配給物件
