リスト要素の前方を参照する処理(1)

特別に新しいことではない、Java標準で 1.6の時代からあることではあるが、
意外と正確に迅速に書けないロジック
(課題)A, B. C,.... と文字列のリストが存在する。
    これを、前の要素を参照しながら抽出処理する。

ListIterator の hasPrevious() と previous() を使う。
注意しなければならないのは、previous() は、参照ポインタが1つ前に移動するので、
進めるには2回 next() を実行することだ。

List<String> list = List.of("A", "B", "C");

for(ListIterator<String> it = list.listIterator(); it.hasNext();) {
    String pre = null;
    if (it.hasPrevious()) {
        pre = it.previous();
        it.next();
    }
    String cur = it.next();
    // TODO 前の要素を認識した処理
    System.out.println("cur="+cur+"  pre="+pre);
}

結果

cur=A  pre=null
cur=B  pre=A
cur=C  pre=B

汎用的にする手段として、
java.util.AbstractMap.SimpleEntry の key, value に置き換えて value を前の要素する。

public static <T> List<SimpleEntry<T, T>> previousReferList(List<T> list){
    List<SimpleEntry<T, T>> rtn = new ArrayList<>();
    for(ListIterator<T> it = list.listIterator(); it.hasNext();) {
        T pre = null;
        if (it.hasPrevious()) {
            pre = it.previous();
            it.next();
        }
        rtn.add(new SimpleEntry<T, T>(it.next(), pre));
    }
    return rtn;
}
public static <T> List<SimpleEntry<T, T>> previousReferList(T...t){
    return previousReferList(Arrays.asList(t));
}
public static <T> List<SimpleEntry<T, T>> previousReferLists(T[] t){
    return previousReferList(Arrays.asList(t));
}

実行

List<String> list = List.of("A", "B", "C");

List<SimpleEntry<String, String>> res = previousReferList(list);
res.stream().forEach(e->{
    // TODO 前の要素は、e.getValue() 
    System.out.println("cur="+e.getKey()+"  pre="+e.getValue());
});

結果

cur=A  pre=null
cur=B  pre=A
cur=C  pre=B

oboe2uran.hatenablog.com