How to pass iterator to method as parameter and how it works ?? any example in java

huangapple go评论60阅读模式
英文:

How to pass iterator to method as parameter and how it works ?? any example in java

问题

如何将迭代器作为参数传递给方法并使其工作?有示例吗?
被调用的方法会像这样:

void someMethod(Iterator<String> data) {

}

我们如何使用这个 "data" 对象... 有示例吗?
需要示例来理解当迭代器作为参数传递给方法时它是如何工作的。

英文:

How to pass iterator to method as parameter and how it works ?? any example .
where callee would look like this :

void someMethod(Iterator&lt;String&gt; data) {     

}

how we can use this "data" object ... Any example

need example to understand how iterator works when passed as parameter to a method.

答案1

得分: 1

private static void method(Iterator iterator) {
iterator.hasNext();

iterator.next();

iterator.forEachRemaining(System.out::println);

}

你可以像你写的那样精确传递 Iterator。

你可以使用 hasNext() 来检查是否有下一个元素,使用 next() 来获取下一个元素。或者你可以遍历集合中剩余的元素。

例如,如果你创建一个包含5个元素的列表,然后调用两次 next(),forEachRemaining() 将使用剩下的3个元素。

forEachRemaining 接受一个 Consumer,所以类似于以下方式:

System.out::println

或者等价于

x -> System.out.println(x)

Consume 是一个关于如何使用参数的指令。

作为使用示例,你可以使用迭代器来遍历 CSV 文件。你可以读取第一行作为标题,然后将其余行解析成对象。

英文:

You can pass Iterator exactly as you wrote

private static void method(Iterator&lt;String&gt; iterator) {
    iterator.hasNext();

    iterator.next();

    iterator.forEachRemaining(System.out::println);

}

You can check if there is next element with hasNext(), you can take next element with next(). Or you can iterate throught elements what left in collection.

for example if you create list with 5 elements and then invoke next() two times

forEachRemaining() will use 3 elements what left.

forEachRemaining accept Consumer so this is something like bellow

System.out::prinln

or equivalent

x -&gt; System.out.println(x)

Consume is an instruction how to use an argument

As example of usage you can use iterator to go throught csv file.
You can read first line as header and then parse rest lines into objects

huangapple
  • 本文由 发表于 2023年4月7日 01:54:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定