CollectionUtil.java 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package me.ag2s.epublib.util;
  2. import java.util.Collection;
  3. import java.util.Enumeration;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. public class CollectionUtil {
  7. /**
  8. * Wraps an Enumeration around an Iterator
  9. * @author paul.siegmann
  10. *
  11. * @param <T>
  12. */
  13. private static class IteratorEnumerationAdapter<T> implements Enumeration<T> {
  14. private final Iterator<T> iterator;
  15. public IteratorEnumerationAdapter(Iterator<T> iter) {
  16. this.iterator = iter;
  17. }
  18. @Override
  19. public boolean hasMoreElements() {
  20. return iterator.hasNext();
  21. }
  22. @Override
  23. public T nextElement() {
  24. return iterator.next();
  25. }
  26. }
  27. /**
  28. * Creates an Enumeration out of the given Iterator.
  29. * @param <T> g
  30. * @param it g
  31. * @return an Enumeration created out of the given Iterator.
  32. */
  33. @SuppressWarnings("unused")
  34. public static <T> Enumeration<T> createEnumerationFromIterator(
  35. Iterator<T> it) {
  36. return new IteratorEnumerationAdapter<>(it);
  37. }
  38. /**
  39. * Returns the first element of the list, null if the list is null or empty.
  40. *
  41. * @param <T> f
  42. * @param list f
  43. * @return the first element of the list, null if the list is null or empty.
  44. */
  45. public static <T> T first(List<T> list) {
  46. if (list == null || list.isEmpty()) {
  47. return null;
  48. }
  49. return list.get(0);
  50. }
  51. /**
  52. * Whether the given collection is null or has no elements.
  53. *
  54. * @param collection g
  55. * @return Whether the given collection is null or has no elements.
  56. */
  57. public static boolean isEmpty(Collection<?> collection) {
  58. return collection == null || collection.isEmpty();
  59. }
  60. }