Close

Java - How to get next or previous item from a Collection?

[Updated: May 21, 2018, Created: May 21, 2018]

Java Collections Java 

Following example shows how to get next or previous item from a java.util.Collection. The flag 'circular' allows to cycle the collection indefinitely.

package com.logicbig.example;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;

public class CollectionNextPrevItem {

  public static <T> T getNext(Collection<T> collection, T target) {
      return getNext(collection, target, false);
  }

  public static <T> T getNext(Collection<T> collection, T target, final boolean circular) {
      if (collection == null) {
          return null;
      }
      Iterator<T> itr = collection.iterator();
      T first = null;
      boolean firstItr = true;
      while (itr.hasNext()) {
          T t = itr.next();
          if (circular && firstItr) {
              first = t;
              firstItr = false;
          }
          if (Objects.equals(t, target)) {
              return itr.hasNext() ? itr.next() : circular ? first : null;
          }
      }
      return null;
  }

  public static <T> T getPrevious(Collection<T> collection, T target) {
      return getPrevious(collection, target, false);
  }

  public static <T> T getPrevious(Collection<T> collection, T target, final boolean circular) {
      if (collection == null) {
          return null;
      }
      Iterator<T> itr = collection.iterator();
      T previous = null;
      boolean firstItr = true;
      while (itr.hasNext()) {
          T t = itr.next();
          if (Objects.equals(t, target)) {
              if (firstItr && circular) {
                  for (; itr.hasNext(); t = itr.next())
                      ;
                  return t;
              } else {
                  return previous;
              }
          }
          previous = t;
          firstItr = false;
      }
      return null;
  }


  public static void main(String[] args) {
      List<String> list = List.of("one", "two", "three", "four");
      String s = getNext(list, "three");
      System.out.println(s);
      s = getPrevious(list, "three");
      System.out.println(s);
      s = getNext(list, "four");
      System.out.println(s);
      s = getPrevious(list, "one");
      System.out.println(s);

      System.out.println("-- circular --");
      s = getNext(list, "four", true);
      System.out.println(s);
      s = getPrevious(list, "one", true);
      System.out.println(s);
  }
}
four
two
null
null
-- circular --
one
four

See Also