简体   繁体   English

用 Java 迭代列表中的两个元素

[英]Iterate by two elements on a list with Java

Im looking for a way to iterate by two elements in Java我正在寻找一种方法来迭代 Java 中的两个元素

For example: i have this list: { "e1", "e2", "e3", "e4" }例如:我有这个列表:{ "e1", "e2", "e3", "e4" }

and i want on first iteration get { "e1", "e2" }, on second { "e2", "e3" }我想在第一次迭代中得到{“e1”,“e2”},在第二次{“e2”,“e3”}

I have already find a way to do this with Python with itertools, like this:我已经找到了使用 Python 和 itertools 执行此操作的方法,如下所示:

import itertools
from itertools import tee

def pairwise(iterable):
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)

...
for e1,e2 in pairwise(list) :
    # creating an element using e1 and e2

I know i can do it manually in Java, but im asking is there's a defined way to do it, Thank you for your help我知道我可以在 Java 中手动执行此操作,但我想问的是是否有明确的方法来执行此操作,谢谢您的帮助

To achieve the task it's more then enough to use a regular loop and return on each step [curent,curent+1] list elements.要完成任务,使用常规循环并在每个步骤上返回[curent,curent+1]列表元素就足够了。

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestList
{
public static void main(String args[])
{
    ArrayList <String> l = new ArrayList(Arrays.asList("a","b","c","d"));
    List al = new TestList().iterateList(l);
    al.forEach(System.out::println);

}
public List iterateList(List l)
{

    ArrayList<String> al = new ArrayList();
    if(l==null || l.size() <= 1)
    {
        //list size should be not_null and greater then 1 : 2_fine
        return null;
    }
    for(int i=0;i<l.size()-1;i++)
    {
        String element = l.get(i)+","+l.get(i+1);
        al.add(element);
    }
    return al;
}

Output: Output:
a,b
b,c
c,d

In Java, it is as simple as follows:在Java中,简单如下:

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> list = List.of("e1", "e2", "e3", "e4");
        for (int i = 0; i < list.size() - 1; i++) {
            System.out.println("(" + list.get(i) + ", " + list.get(i + 1) + ")");
        }
    }
}

Output: Output:

(e1, e2)
(e2, e3)
(e3, e4)

After many searchs i think the only way in Java is to do it manually经过多次搜索,我认为 Java 中唯一的方法是手动完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM