簡體   English   中英

為什么一個可迭代的計數返回 1?

[英]Why count of an iterable returns 1?

這是 pom.xml

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

這是 model

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class WebsiteUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

private String name;
private String email;

public long getId() {
    return id;
}

public void setId(long id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}
}

這是用戶存儲庫

@RepositoryRestResource(collectionResourceRel = "users", path = "users")
public interface UserRepository extends PagingAndSortingRepository<WebsiteUser, Long> {
List<WebsiteUser> findByName(@RequestParam("name") String name);
}

這是我的數據加載器:

@Component

公共 class DataLoader 實現 CommandLineRunner {

private static final Logger log = LogManager.getFormatterLogger(DataLoader.class);

private final UserRepository userRepository;

public DataLoader(UserRepository userRepository) {
    this.userRepository = userRepository;
}

@Override
public void run(String... args) throws Exception {

    Iterable<WebsiteUser> data = userRepository.findAll();

    long count = Stream.of(data).count();
    log.info("counted:" + count);
    log.info("data:" + data);

}
}

日志返回以下值:

計數:1

數據:[]

我不明白這個返回值。 [] 是空的,應該返回 0 而不是 1。你能解釋一下為什么會這樣嗎? 我怎樣才能得到 0 而不是 1?

你沒有數據。

Stream.of(data)生成一個 stream 的可迭代對象。 這 stream 包含 1 項( data ),空的迭代,然后將盡職盡責地 go:是的。 1 個空 stream。 計數為 1。

一般來說,你應該讓 collections 把自己變成流——無論 findAll 返回什么,它都比 Iterable 更具體,而且它可能有一個 stream() 方法。 如果沒有,您應該升級該依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM