gpt4 book ai didi

java - 如何统计Stream已处理的元素数量?

转载 作者:行者123 更新时间:2023-11-30 02:50:09 26 4
gpt4 key购买 nike

这是我的例子

我有一个 Person 类,看起来像

class Person {
List<String> keys;
Map<String, String> attributes;

public Person(List<String> keys, Map<String, String> attributes) {
this.keys = keys;
this.attributes = attributes;
}

public List<String> getKeys() {
return keys;
}

public Map<String, String> getAttributes() {
return attributes;
}
}

我将一些persons作为流处理,并将它们转换为JSON作为

  @Test
public void testPersonStreamToFile() throws Exception {
Person person1 = new Person(Collections.singletonList("key1"), Collections.singletonMap("person1", "key1"));
Person person2 = new Person(Collections.singletonList("key2"), Collections.singletonMap("person2", "key2"));

File file = temporaryFolder.newFile("personStream.txt");
System.out.println(file.toString());

List<Person> persons = Arrays.asList(person1, person2);

Stream<String> personStream = persons
.stream()
.map(WorkflowTest::mapToJsonString);


Files.write(Paths.get(file.toURI()), (Iterable<String>) personStream::iterator);
System.out.println("Done");
}

必填当我处理流时,我想保留一个 Counter 来告诉我在程序结束时有多少 person 被转换为 JSON

如何使用 Streams 实现此目的?

最佳答案

您可以使用如下的peek操作:

AtomicInteger counter = new AtomicInteger(0);

Stream<String> personStream = persons
.stream()
.map(WorkflowTest::mapToJsonString)
.peek(str -> counter.incrementAndGet());

操作后 counter.get() 将显示此处调用 mapToJsonString 的次数。

关于java - 如何统计Stream已处理的元素数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38962449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com