Java Tutorial/Collections/Iterator
Содержание
- 1 An iterator that breaks text into lines. The result is equal to BufferedReader.readLine().
- 2 An Iterator that returns the elements of a specified array, or other iterators etc.
- 3 An Iterator that wraps a number of Iterators
- 4 An Iterator wrapper for an Enumeration.
- 5 An Iterator wrapper for an Object[], allow us to deal with all array like structures in a consistent manner.
- 6 Array Iterator
- 7 Create singleton Iterator
- 8 Cyclic Iteration
- 9 Gets the child of the specified element having the specified unique name
- 10 Implements an java.util.Iterator over any array
- 11 Iterate a Collection and remove an item (Exception, wrong version)
- 12 Iterate through a Collection using Java Iterator
- 13 Iterate through elements of Java LinkedList using Iterator
- 14 Iterator class for sparse values in an array.
- 15 Iterator class for values contained in an array range.
- 16 Iterator from LinkedList
- 17 Iterator Union of Iterators
- 18 Iterator Utils
- 19 Protects an given iterator by preventing calls to remove().
- 20 Remove an element from Collection using Java Iterator
- 21 Returns an iterator over the children of the given element with the given tag name
- 22 Sorted Iterator
- 23 This constructs an Iterator over each day in a date range defined by a focus date and range style.
- 24 Traverse through ArrayList in forward direction using Java ListIterator
- 25 Traverse through ArrayList in reverse direction using Java ListIterator
- 26 Treat an Iterator as an Iterable
- 27 Use an Iterator to cycle through a collection in the forward direction.
- 28 Use Iterator to loop through ArrayList
- 29 Use Iterator to loop through the HashMap class
An iterator that breaks text into lines. The result is equal to BufferedReader.readLine().
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ----------------------
* LineBreakIterator.java
* ----------------------
* (C)opyright 2003, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): David Gilbert (for Object Refinery Limited);
*
* $Id: LineBreakIterator.java,v 1.4 2005/11/03 09:55:26 mungady Exp $
*
* Changes
* -------
* 13-03-2003 : Initial version
*/
import java.util.Iterator;
/**
* An iterator that breaks text into lines. The result is equal to
* BufferedReader.readLine().
*
* @author Thomas Morgner
*/
public class LineBreakIterator implements Iterator {
/** A useful constant. */
public static final int DONE = -1;
/** Storage for the text. */
private char[] text;
/** The current position. */
private int position;
/**
* Default constructor.
*/
public LineBreakIterator() {
setText("");
}
/**
* Creates a new line break iterator.
*
* @param text
* the text to be broken up.
*/
public LineBreakIterator(final String text) {
setText(text);
}
/**
* Returns the position of the next break.
*
* @return A position.
*/
public synchronized int nextPosition() {
if (this.text == null) {
return DONE;
}
if (this.position == DONE) {
return DONE;
}
// recognize \n, \r, \r\n
final int nChars = this.text.length;
int nextChar = this.position;
for (;;) {
if (nextChar >= nChars) {
/* End of text reached */
this.position = DONE;
return DONE;
}
boolean eol = false;
char c = 0;
int i;
// search the next line break, either \n or \r
for (i = nextChar; i < nChars; i++) {
c = this.text[i];
if ((c == "\n") || (c == "\r")) {
eol = true;
break;
}
}
nextChar = i;
if (eol) {
nextChar++;
if (c == "\r") {
if ((nextChar < nChars) && (this.text[nextChar] == "\n")) {
nextChar++;
}
}
this.position = nextChar;
return (this.position);
}
}
}
/**
* Same like next(), but returns the End-Of-Text as if there was a linebreak
* added (Reader.readLine() compatible)
*
* @return The next position.
*/
public int nextWithEnd() {
final int pos = this.position;
if (pos == DONE) {
return DONE;
}
if (pos == this.text.length) {
this.position = DONE;
return DONE;
}
final int retval = nextPosition();
if (retval == DONE) {
return this.text.length;
}
return retval;
}
/**
* Returns the text to be broken up.
*
* @return The text.
*/
public String getText() {
return new String(this.text);
}
/**
* Sets the text to be broken up.
*
* @param text
* the text.
*/
public void setText(final String text) {
this.position = 0;
this.text = text.toCharArray();
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return (this.position != DONE);
}
/**
* Returns the next element in the iteration.
*
* @return the next element in the iteration.
*/
public Object next() {
if (this.position == DONE) {
// allready at the end ...
return null;
}
final int lastFound = this.position;
int pos = nextWithEnd();
if (pos == DONE) {
// the end of the text has been reached ...
return new String(this.text, lastFound, this.text.length - lastFound);
}
// step one char back
if (pos > 0) {
final int end = lastFound;
for (; ((pos) > end) && ((this.text[pos - 1] == "\n") || this.text[pos - 1] == "\r"); pos--) {
// search the end of the current linebreak sequence ..
}
}
// System.out.println ("text: " + new String (text));
// System.out.println ("pos: " + pos + " lastFound: " + lastFound);
return new String(this.text, lastFound, pos - lastFound);
}
/**
*
* Removes from the underlying collection the last element returned by the
* iterator (optional operation). This method can be called only once per call
* to <tt>next</tt>. The behavior of an iterator is unspecified if the
* underlying collection is modified while the iteration is in progress in any
* way other than by calling this method.
*
* @exception UnsupportedOperationException
* if the <tt>remove</tt> operation is not supported by this
* Iterator.
* @exception IllegalStateException
* if the <tt>next</tt> method has not yet been called, or the
* <tt>remove</tt> method has already been called after the
* last call to the <tt>next</tt> method.
*/
public void remove() {
throw new UnsupportedOperationException("This iterator is read-only.");
}
}
An Iterator that returns the elements of a specified array, or other iterators etc.
/* Copyright (c) 2001-2009, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* An Iterator that returns the elements of a specified array, or other
* iterators etc. The collection of objects returned depends on the
* constructor used.
*
* Based on similar Enumerator code by boucherb@users
*
* @author fred@users
* @version 1.9.0
* @since HSQLDB 1.7.2
*/
public class WrapperIterator implements Iterator {
private static final Object[] emptyelements = new Object[0];
private Object[] elements;
private int i;
// chained iterators
private boolean chained;
private Iterator it1;
private Iterator it2;
/** return only not null elements */
private boolean notNull;
/**
* Constructor for an empty iterator.
*/
public WrapperIterator() {
this.elements = emptyelements;
}
/**
* Constructor for all elements of the specified array.
*
* @param elements the array of objects to enumerate
*/
public WrapperIterator(Object[] elements) {
this.elements = elements;
}
/**
* Constructor for not-null elements of specified array.
*
* @param elements the array of objects to iterate
*/
public WrapperIterator(Object[] elements, boolean notNull) {
this.elements = elements;
this.notNull = notNull;
}
/**
* Constructor for a singleton object iterator
*
* @param element the single object to iterate
*/
public WrapperIterator(Object element) {
this.elements = new Object[]{ element };
}
/**
* Constructor for a chained iterator that returns the elements of the two
* specified iterators.
*/
public WrapperIterator(Iterator it1, Iterator it2) {
this.it1 = it1;
this.it2 = it2;
chained = true;
}
/**
* Tests if this iterator contains more elements.
*
* @return <code>true</code> if this iterator contains more elements;
* <code>false</code> otherwise.
*/
public boolean hasNext() {
// for chained iterators
if (chained) {
if (it1 == null) {
if (it2 == null) {
return false;
}
if (it2.hasNext()) {
return true;
}
it2 = null;
return false;
} else {
if (it1.hasNext()) {
return true;
}
it1 = null;
return hasNext();
}
}
// for other interators
if (elements == null) {
return false;
}
for (; notNull && i < elements.length && elements[i] == null; i++) {}
if (i < elements.length) {
return true;
} else {
// release elements for garbage collection
elements = null;
return false;
}
}
/**
* Returns the next element.
*
* @return the next element
* @throws NoSuchElementException if there is no next element
*/
public Object next() {
// for chained iterators
if (chained) {
if (it1 == null) {
if (it2 == null) {
throw new NoSuchElementException();
}
if (it2.hasNext()) {
return it2.next();
}
it2 = null;
next();
} else {
if (it1.hasNext()) {
return it1.next();
}
it1 = null;
next();
}
}
// for other itertors
if (hasNext()) {
return elements[i++];
}
throw new NoSuchElementException();
}
public int nextInt() {
throw new NoSuchElementException();
}
public long nextLong() {
throw new NoSuchElementException();
}
public void remove() {
throw new NoSuchElementException();
}
public void setValue(Object value) {
throw new NoSuchElementException();
}
}
An Iterator that wraps a number of Iterators
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
import java.util.Iterator;
import java.util.List;
/**
* An JoinedIterator is an Iterator that wraps a number of Iterators.
*
* This class makes multiple iterators look like one to the caller.
* When any method from the Iterator interface is called, the JoinedIterator
* will delegate to a single underlying Iterator. The JoinedIterator will
* invoke the Iterators in sequence until all Iterators are exhausted.
*
*/
public class JoinedIterator implements Iterator {
private static final Iterator[] ITERATORS = {};
// wrapped iterators
private Iterator[] iterators;
// index of current iterator in the wrapped iterators array
private int currentIteratorIndex;
// the current iterator
private Iterator currentIterator;
// the last used iterator
private Iterator lastUsedIterator;
public JoinedIterator(List iterators) {
this( (Iterator[]) iterators.toArray(ITERATORS) );
}
public JoinedIterator(Iterator[] iterators) {
if( iterators==null )
throw new NullPointerException("Unexpected NULL iterators argument");
this.iterators = iterators;
}
public JoinedIterator(Iterator first, Iterator second) {
this( new Iterator[] { first, second } );
}
public boolean hasNext() {
updateCurrentIterator();
return currentIterator.hasNext();
}
public Object next() {
updateCurrentIterator();
return currentIterator.next();
}
public void remove() {
updateCurrentIterator();
lastUsedIterator.remove();
}
// call this before any Iterator method to make sure that the current Iterator
// is not exhausted
protected void updateCurrentIterator() {
if (currentIterator == null) {
if( iterators.length==0 ) {
currentIterator = EmptyIterator.emptyIterator;
}
else {
currentIterator = iterators[0];
}
// set last used iterator here, in case the user calls remove
// before calling hasNext() or next() (although they shouldn"t)
lastUsedIterator = currentIterator;
}
while (! currentIterator.hasNext() && currentIteratorIndex < iterators.length - 1) {
currentIteratorIndex++;
currentIterator = iterators[currentIteratorIndex];
}
}
}
/* Copyright 2004 BEA Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class EmptyIterator implements java.util.Iterator {
public static final EmptyIterator emptyIterator = new EmptyIterator();
public boolean hasNext() { return false; }
public Object next() { return null; }
public void remove() {
throw new UnsupportedOperationException();
}
}
An Iterator wrapper for an Enumeration.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Enumeration;
import java.util.Iterator;
/**
* An Iterator wrapper for an Enumeration.
*
* @author
* @version $Id: EnumerationIterator.java 463298 2006-10-12 16:10:32Z henning $
*/
public class EnumerationIterator implements Iterator {
/**
* The enumeration to iterate.
*/
private Enumeration enumeration = null;
/**
* Creates a new iteratorwrapper instance for the specified Enumeration.
*
* @param enumeration
* The Enumeration to wrap.
*/
public EnumerationIterator(Enumeration enumeration) {
this.enumeration = enumeration;
}
/**
* Move to next element in the array.
*
* @return The next object in the array.
*/
public Object next() {
return enumeration.nextElement();
}
/**
* Check to see if there is another element in the array.
*
* @return Whether there is another element.
*/
public boolean hasNext() {
return enumeration.hasMoreElements();
}
/**
* Unimplemented. No analogy in Enumeration
*/
public void remove() {
// not implemented
}
}
An Iterator wrapper for an Object[], allow us to deal with all array like structures in a consistent manner.
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
/**
*
* An Iterator wrapper for an Object[]. This will
* allow us to deal with all array like structures
* in a consistent manner.
*
*
* WARNING : this class"s operations are NOT synchronized.
* It is meant to be used in a single thread, newly created
* for each use in the #foreach() directive.
* If this is used or shared, synchronize in the
* next() method.
*
*
* @author
* @version $Id: ArrayIterator.java 463298 2006-10-12 16:10:32Z henning $
*/
public class ArrayIterator implements Iterator
{
/**
* The objects to iterate.
*/
private Object array;
/**
* The current position and size in the array.
*/
private int pos;
private int size;
/**
* Creates a new iterator instance for the specified array.
*
* @param array The array for which an iterator is desired.
*/
public ArrayIterator(Object array)
{
/*
* if this isn"t an array, then throw. Note that this is
* for internal use - so this should never happen - if it does
* we screwed up.
*/
if ( !array.getClass().isArray() )
{
throw new IllegalArgumentException(
"Programmer error : internal ArrayIterator invoked w/o array");
}
this.array = array;
pos = 0;
size = Array.getLength( this.array );
}
/**
* Move to next element in the array.
*
* @return The next object in the array.
*/
public Object next()
{
if (pos < size )
return Array.get( array, pos++);
/*
* we screwed up...
*/
throw new NoSuchElementException("No more elements: " + pos +
" / " + size);
}
/**
* Check to see if there is another element in the array.
*
* @return Whether there is another element.
*/
public boolean hasNext()
{
return (pos < size );
}
/**
* No op--merely added to satify the <code>Iterator</code> interface.
*/
public void remove()
{
throw new UnsupportedOperationException();
}
}
Array Iterator
/**
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Apr 17, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
public class ArrayUtilities {
/**
*
*/
private ArrayUtilities() {
super();
}
public static Iterator iterator(Object[] array, int offset, int length) {
return new ArrayIterator(array, offset, length);
}
private static class ArrayIterator implements Iterator {
private final Object[] array;
private final int top;
private int offset;
public ArrayIterator(Object[] array, int offset, int length) {
this.array = array;
this.offset = offset;
this.top = offset + length;
}
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {
return this.offset < this.top;
}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public Object next() {
return this.array[this.offset++];
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
Create singleton Iterator
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Jun 9, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
class CollectionUtilities {
/**
*
*/
private CollectionUtilities() {
super();
}
public static Enumeration getIteratorEnumeration(final Iterator i) {
return new Enumeration() {
public boolean hasMoreElements() {
return i.hasNext();
}
public Object nextElement() {
return i.next();
}
};
}
public static Iterator iteratorUnion(final Iterator[] iterators) {
return new Iterator() {
private int iteratorIndex = 0;
private Iterator current = iterators.length > 0 ? iterators[0] : null;
public boolean hasNext() {
for(;;) {
if(current == null) {
return false;
}
if(current.hasNext()) {
return true;
}
iteratorIndex++;
current = iteratorIndex >= iterators.length ? null : iterators[iteratorIndex];
}
}
public Object next() {
for(;;) {
if(this.current == null) {
throw new NoSuchElementException();
}
try {
return this.current.next();
} catch(NoSuchElementException nse) {
this.iteratorIndex++;
this.current = this.iteratorIndex >= iterators.length ? null : iterators[this.iteratorIndex];
}
}
}
public void remove() {
if(this.current == null) {
throw new NoSuchElementException();
}
this.current.remove();
}
};
}
public static Collection reverse(Collection collection) {
LinkedList newCollection = new LinkedList();
Iterator i = collection.iterator();
while(i.hasNext()) {
newCollection.addFirst(i.next());
}
return newCollection;
}
public static Iterator singletonIterator(final Object item) {
return new Iterator() {
private boolean gotItem = false;
public boolean hasNext() {
return !this.gotItem;
}
public Object next() {
if(this.gotItem) {
throw new NoSuchElementException();
}
this.gotItem = true;
return item;
}
public void remove() {
if(!this.gotItem) {
this.gotItem = true;
}
else {
throw new NoSuchElementException();
}
}
};
}
}
Cyclic Iteration
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.SortedMap;
/** Provide an cyclic {@link Iterator} for a {@link SortedMap}.
* The {@link Iterator} navigates the entries of the map
* according to the map"s ordering.
* If the {@link Iterator} hits the last entry of the map,
* it will then continue from the first entry.
*/
public class CyclicIteration<K, V> implements Iterable<Map.Entry<K, V>> {
private final SortedMap<K, V> navigablemap;
private final SortedMap<K, V> tailmap;
private final K startingkey;
/** Construct an {@link Iterable} object,
* so that an {@link Iterator} can be created
* for iterating the given {@link SortedMap}.
* The iteration begins from the starting key exclusively.
*/
public CyclicIteration(SortedMap<K, V> navigablemap, K startingkey) {
this.startingkey = startingkey;
if (navigablemap == null || navigablemap.isEmpty()) {
this.navigablemap = null;
this.tailmap = null;
}
else {
this.navigablemap = navigablemap;
this.tailmap = navigablemap.tailMap(startingkey);
}
}
/** {@inheritDoc} */
public Iterator<Map.Entry<K, V>> iterator() {
return new CyclicIterator();
}
/** An {@link Iterator} for {@link CyclicIteration}. */
private class CyclicIterator implements Iterator<Map.Entry<K, V>> {
private boolean hasnext;
private Iterator<Map.Entry<K, V>> i;
/** The first entry to begin. */
private final Map.Entry<K, V> first;
/** The next entry. */
private Map.Entry<K, V> next;
private CyclicIterator() {
hasnext = navigablemap != null;
if (hasnext) {
i = tailmap.entrySet().iterator();
Map.Entry<K, V> e = nextEntry();
if (e.getKey().equals(startingkey)) {
e = nextEntry();
}
first = e;
next = first;
}
else {
i = null;
first = null;
next = null;
}
}
private Map.Entry<K, V> nextEntry() {
if (!i.hasNext()) {
i = navigablemap.entrySet().iterator();
}
return i.next();
}
/** {@inheritDoc} */
public boolean hasNext() {
return hasnext;
}
/** {@inheritDoc} */
public Map.Entry<K, V> next() {
if (!hasnext) {
throw new NoSuchElementException();
}
final Map.Entry<K, V> curr = next;
next = nextEntry();
hasnext = !next.equals(first);
return curr;
}
/** Not supported */
public void remove() {
throw new UnsupportedOperationException("Not supported");
}
}
}
Gets the child of the specified element having the specified unique name
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A utility class to cover up the rough bits of xml parsing
*
* @author
* @version $Revision: 2787 $
*/
@SuppressWarnings("unchecked")
public class XmlHelper {
/**
* Returns an iterator over the children of the given element with the given
* tag name.
*
* @param element
* The parent element
* @param tagName
* The name of the desired child
* @return An interator of children or null if element is null.
*/
public static Iterator getChildrenByTagName(Element element, String tagName) {
if (element == null)
return null;
// getElementsByTagName gives the corresponding elements in the whole
// descendance. We want only children
NodeList children = element.getChildNodes();
ArrayList goodChildren = new ArrayList();
for (int i = 0; i < children.getLength(); i++) {
Node currentChild = children.item(i);
if (currentChild.getNodeType() == Node.ELEMENT_NODE
&& ((Element) currentChild).getTagName().equals(tagName)) {
goodChildren.add(currentChild);
}
}
return goodChildren.iterator();
}
/**
* Gets the child of the specified element having the specified unique name.
* If there are more than one children elements with the same name and
* exception is thrown.
*
* @param element
* The parent element
* @param tagName
* The name of the desired child
* @return The named child.
*
* @throws Exception
* Child was not found or was not unique.
*/
public static Element getUniqueChild(Element element, String tagName) throws Exception {
Iterator goodChildren = getChildrenByTagName(element, tagName);
if (goodChildren != null && goodChildren.hasNext()) {
Element child = (Element) goodChildren.next();
if (goodChildren.hasNext()) {
throw new Exception("expected only one " + tagName + " tag");
}
return child;
} else {
throw new Exception("expected one " + tagName + " tag");
}
}
/**
* Gets the child of the specified element having the specified name. If the
* child with this name doesn"t exist then null is returned instead.
*
* @param element
* the parent element
* @param tagName
* the name of the desired child
* @return either the named child or null
* @throws Exception
*/
public static Element getOptionalChild(Element element, String tagName) throws Exception {
return getOptionalChild(element, tagName, null);
}
/**
* Gets the child of the specified element having the specified name. If the
* child with this name doesn"t exist then the supplied default element is
* returned instead.
*
* @param element
* the parent element
* @param tagName
* the name of the desired child
* @param defaultElement
* the element to return if the child doesn"t exist
* @return either the named child or the supplied default
* @throws Exception
*/
public static Element getOptionalChild(Element element, String tagName, Element defaultElement)
throws Exception {
Iterator goodChildren = getChildrenByTagName(element, tagName);
if (goodChildren != null && goodChildren.hasNext()) {
Element child = (Element) goodChildren.next();
if (goodChildren.hasNext()) {
throw new Exception("expected only one " + tagName + " tag");
}
return child;
} else {
return defaultElement;
}
}
/**
* Get the content of the given element.
*
* @param element
* The element to get the content for.
* @return The content of the element or null.
* @throws Exception
*/
public static String getElementContent(final Element element) throws Exception {
return getElementContent(element, null);
}
/**
* Get the content of the given element.
*
* @param element
* The element to get the content for.
* @param defaultStr
* The default to return when there is no content.
* @return The content of the element or the default.
* @throws Exception
*/
public static String getElementContent(Element element, String defaultStr) throws Exception {
if (element == null)
return defaultStr;
NodeList children = element.getChildNodes();
String result = "";
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.TEXT_NODE
|| children.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
result += children.item(i).getNodeValue();
} else if (children.item(i).getNodeType() == Node.ruMENT_NODE) {
// Ignore comment nodes
}
}
return result.trim();
}
/**
* Macro to get the content of a unique child element.
*
* @param element
* The parent element.
* @param tagName
* The name of the desired child.
* @return The element content or null.
* @throws Exception
*/
public static String getUniqueChildContent(Element element, String tagName) throws Exception {
return getElementContent(getUniqueChild(element, tagName));
}
/**
* Macro to get the content of an optional child element.
*
* @param element
* The parent element.
* @param tagName
* The name of the desired child.
* @return The element content or null.
* @throws Exception
*/
public static String getOptionalChildContent(Element element, String tagName) throws Exception {
return getElementContent(getOptionalChild(element, tagName));
}
public static boolean getOptionalChildBooleanContent(Element element, String name)
throws Exception {
Element child = getOptionalChild(element, name);
if (child != null) {
String value = getElementContent(child).toLowerCase();
return value.equals("true") || value.equals("yes");
}
return false;
}
}
Implements an java.util.Iterator over any array
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Array;
import java.util.NoSuchElementException;
/**
* Implements an {@link java.util.Iterator Iterator} over any array.
*
* The array can be either an array of object or of primitives. If you know
* that you have an object array, the
* {@link org.apache.rumons.collections.iterators.ObjectArrayIterator ObjectArrayIterator}
* class is a better choice, as it will perform better.
*
* The iterator implements a {@link #reset} method, allowing the reset of
* the iterator back to the start if required.
*
* @since Commons Collections 1.0
* @version $Revision$ $Date$
*
* @author James Strachan
* @author Mauricio S. Moura
* @author Michael A. Smith
* @author Neil O"Toole
* @author Stephen Colebourne
*/
public class ArrayIterator implements java.util.Iterator {
/** The array to iterate over */
protected Object array;
/** The end index to loop to */
protected int endIndex = 0;
/** The current iterator index */
protected int index = 0;
/**
* Constructs an ArrayIterator that will iterate over the values in the
* specified array.
*
* @param array the array to iterate over.
* @throws IllegalArgumentException if <code>array</code> is not an array.
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
public ArrayIterator(final Object array) {
setArray(array);
}
/**
* Checks whether the index is valid or not.
*
* @param bound the index to check
* @param type the index type (for error messages)
* @throws IndexOutOfBoundsException if the index is invalid
*/
protected void checkBound(final int bound, final String type ) {
if (bound > this.endIndex) {
throw new ArrayIndexOutOfBoundsException(
"Attempt to make an ArrayIterator that " + type +
"s beyond the end of the array. "
);
}
if (bound < 0) {
throw new ArrayIndexOutOfBoundsException(
"Attempt to make an ArrayIterator that " + type +
"s before the start of the array. "
);
}
}
// Iterator interface
//-----------------------------------------------------------------------
/**
* Returns true if there are more elements to return from the array.
*
* @return true if there is a next element to return
*/
public boolean hasNext() {
return (index < endIndex);
}
/**
* Returns the next element in the array.
*
* @return the next element in the array
* @throws NoSuchElementException if all the elements in the array
* have already been returned
*/
public Object next() {
if (hasNext() == false) {
throw new NoSuchElementException();
}
return Array.get(array, index++);
}
/**
* Throws {@link UnsupportedOperationException}.
*
* @throws UnsupportedOperationException always
*/
public void remove() {
throw new UnsupportedOperationException("remove() method is not supported");
}
// Properties
//-----------------------------------------------------------------------
/**
* Gets the array that this iterator is iterating over.
*
* @return the array this iterator iterates over, or <code>null</code> if
* the no-arg constructor was used and {@link #setArray(Object)} has never
* been called with a valid array.
*/
public Object getArray() {
return array;
}
/**
* Sets the array that the ArrayIterator should iterate over.
*
* If an array has previously been set (using the single-arg constructor
* or this method) then that array is discarded in favour of this one.
* Iteration is restarted at the start of the new array.
* Although this can be used to reset iteration, the {@link #clear()} method
* is a more effective choice.
*
* @param array the array that the iterator should iterate over.
* @throws IllegalArgumentException if <code>array</code> is not an array.
* @throws NullPointerException if <code>array</code> is <code>null</code>
*/
private void setArray(final Object array) {
// Array.getLength throws IllegalArgumentException if the object is not
// an array or NullPointerException if the object is null. This call
// is made before saving the array and resetting the index so that the
// array iterator remains in a consistent state if the argument is not
// an array or is null.
this.endIndex = Array.getLength(array);
this.array = array;
this.index = 0;
}
}
Iterate a Collection and remove an item (Exception, wrong version)
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<String> list = new ArrayList<String>();
list.add("A");
list.add("B");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
list.add("C");
for (String s : list) {
if (s.equals("B")) {
list.remove("B");
}
System.out.println(s);
}
}
}
/*A
B
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at Main.main(Main.java:17)
*/
Iterate through a Collection using Java Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
Iterator itr = aList.iterator();
// iterate through the ArrayList values using Iterator"s hasNext and next methods
while (itr.hasNext()){
System.out.println(itr.next());
}
}
}
Iterate through elements of Java LinkedList using Iterator
import java.util.Iterator;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
LinkedList<String> lList = new LinkedList<String>();
lList.add("1");
lList.add("2");
lList.add("3");
lList.add("4");
lList.add("5");
Iterator itr = lList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Iterator class for sparse values in an array.
/*
* Copyright (c) 2000-2007, Dennis M. Sosnoski. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. Neither the name of JiBX nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator class for sparse values in an array. This type of iterator
* can be used for an object array which has references interspersed with
* <code>null</code>s.
*
* @author Dennis M. Sosnoski
*/
public class SparseArrayIterator implements Iterator
{
/** Empty iterator. */
public static final SparseArrayIterator EMPTY_ITERATOR =
new SparseArrayIterator(new Object[0]);
/** Array supplying values for iteration. */
private Object[] m_array;
/** Offset of next iteration value. */
private int m_offset;
/**
* Internal constructor.
*
* @param array array containing values to be iterated
*/
private SparseArrayIterator(Object[] array) {
m_array = array;
m_offset = -1;
advance();
}
/**
* Advance to next iteration value. This advances the current position in
* the array to the next non-<code>null</code> value.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
protected boolean advance() {
while (++m_offset < m_array.length) {
if (m_array[m_offset] != null) {
return true;
}
}
return false;
}
/**
* Check for iteration element available.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
public boolean hasNext() {
return m_offset < m_array.length;
}
/**
* Get next iteration element.
*
* @return next iteration element
* @exception NoSuchElementException if past end of iteration
*/
public Object next() {
if (m_offset < m_array.length) {
Object result = m_array[m_offset];
advance();
return result;
} else {
throw new NoSuchElementException();
}
}
/**
* Remove element from iteration. This optional operation is not supported
* and always throws an exception.
*
* @exception UnsupportedOperationException for unsupported operation
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Build iterator.
*
* @param array array containing values to be iterated (may be
* <code>null</code>)
* @return constructed iterator
*/
public static Iterator buildIterator(Object[] array) {
if (array == null || array.length == 0) {
return EMPTY_ITERATOR;
} else {
return new SparseArrayIterator(array);
}
}
}
Iterator class for values contained in an array range.
/*
Copyright (c) 2000-2005, Dennis M. Sosnoski.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of JiBX nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Iterator class for values contained in an array range. This type of iterator
* can be used for any contiguous range of items in an object array.
*
* @author Dennis M. Sosnoski
* @version 1.1
*/
public class ArrayRangeIterator implements Iterator
{
/** Empty iterator used whenever possible. */
public static final ArrayRangeIterator EMPTY_ITERATOR =
new ArrayRangeIterator(null, 0, 0);
/** Array supplying values for iteration. */
protected Object[] m_array;
/** Offset of next iteration value. */
protected int m_offset;
/** Ending offset for values. */
protected int m_limit;
/**
* Internal constructor.
*
* @param array array containing values to be iterated
* @param start starting offset in array
* @param limit offset past end of values
*/
private ArrayRangeIterator(Object[] array, int start, int limit) {
m_array = array;
m_offset = start;
m_limit = limit;
}
/**
* Check for iteration element available.
*
* @return <code>true</code> if element available, <code>false</code> if
* not
*/
public boolean hasNext() {
return m_offset < m_limit;
}
/**
* Get next iteration element.
*
* @return next iteration element
* @exception NoSuchElementException if past end of iteration
*/
public Object next() {
if (m_offset < m_limit) {
return m_array[m_offset++];
} else {
throw new NoSuchElementException();
}
}
/**
* Remove element from iteration. This optional operation is not supported
* and always throws an exception.
*
* @exception UnsupportedOperationException for unsupported operation
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Build iterator.
*
* @param array array containing values to be iterated (may be
* <code>null</code>)
* @param start starting offset in array
* @param limit offset past end of values
* @return constructed iterator
*/
public static Iterator buildIterator(Object[] array, int start, int limit) {
if (array == null || start >= limit) {
return EMPTY_ITERATOR;
} else {
return new ArrayRangeIterator(array, start, limit);
}
}
}
Iterator from LinkedList
import java.util.Iterator;
import java.util.LinkedList;
public class LinkedListExample {
public static void main(String[] args) {
// Create a new LinkedList
LinkedList<Integer> list = new LinkedList<Integer>();
// Add Items to the array list
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(3));
list.add(new Integer(4));
list.add(new Integer(5));
list.add(new Integer(6));
list.add(new Integer(7));
list.add(new Integer(8));
list.add(new Integer(9));
list.add(new Integer(10));
// Use iterator to display the values
for (Iterator i = list.iterator(); i.hasNext();) {
Integer integer = (Integer) i.next();
System.out.println(integer);
}
// Remove the element at index 5 (value=6)
list.remove(5);
// Set the value at index 5, this overwrites the value 7
list.set(5, new Integer(66));
// Use the linked list as a queue:
// add an object to the end of the list (queue)
// remove an item from the head of the list (queue)
list.addLast(new Integer(11));
Integer head = (Integer) list.removeFirst();
System.out.println("Head: " + head);
// Use iterator to display the values
for (Iterator i = list.iterator(); i.hasNext();) {
Integer integer = (Integer) i.next();
System.out.println(integer);
}
}
}
Iterator Union of Iterators
/*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
/*
* Created on Jun 9, 2005
*/
import java.util.*;
/**
* @author J. H. S.
*/
class CollectionUtilities {
/**
*
*/
private CollectionUtilities() {
super();
}
public static Enumeration getIteratorEnumeration(final Iterator i) {
return new Enumeration() {
public boolean hasMoreElements() {
return i.hasNext();
}
public Object nextElement() {
return i.next();
}
};
}
public static Iterator iteratorUnion(final Iterator[] iterators) {
return new Iterator() {
private int iteratorIndex = 0;
private Iterator current = iterators.length > 0 ? iterators[0] : null;
public boolean hasNext() {
for(;;) {
if(current == null) {
return false;
}
if(current.hasNext()) {
return true;
}
iteratorIndex++;
current = iteratorIndex >= iterators.length ? null : iterators[iteratorIndex];
}
}
public Object next() {
for(;;) {
if(this.current == null) {
throw new NoSuchElementException();
}
try {
return this.current.next();
} catch(NoSuchElementException nse) {
this.iteratorIndex++;
this.current = this.iteratorIndex >= iterators.length ? null : iterators[this.iteratorIndex];
}
}
}
public void remove() {
if(this.current == null) {
throw new NoSuchElementException();
}
this.current.remove();
}
};
}
public static Collection reverse(Collection collection) {
LinkedList newCollection = new LinkedList();
Iterator i = collection.iterator();
while(i.hasNext()) {
newCollection.addFirst(i.next());
}
return newCollection;
}
public static Iterator singletonIterator(final Object item) {
return new Iterator() {
private boolean gotItem = false;
public boolean hasNext() {
return !this.gotItem;
}
public Object next() {
if(this.gotItem) {
throw new NoSuchElementException();
}
this.gotItem = true;
return item;
}
public void remove() {
if(!this.gotItem) {
this.gotItem = true;
}
else {
throw new NoSuchElementException();
}
}
};
}
}
Iterator Utils
/*
* Distributed as part of debuggen v.0.1.0
*
* Copyright (C) 2005 Machinery For Change, Inc.
*
* Author: Steve Waldman <swaldman@mchange.ru>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 2.1, as
* published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software; see the file LICENSE. If not, write to the
* Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*/
import java.util.*;
import java.lang.reflect.Array;
public final class IteratorUtils
{
public final static Iterator EMPTY_ITERATOR = new Iterator()
{
public boolean hasNext()
{ return false; }
public Object next()
{ throw new NoSuchElementException(); }
public void remove()
{ throw new IllegalStateException(); }
};
public static Iterator oneElementUnmodifiableIterator(final Object elem)
{
return new Iterator()
{
boolean shot = false;
public boolean hasNext() { return (!shot); }
public Object next()
{
if (shot)
throw new NoSuchElementException();
else
{
shot = true;
return elem;
}
}
public void remove()
{ throw new UnsupportedOperationException("remove() not supported."); }
};
}
public static boolean equivalent(Iterator ii, Iterator jj)
{
while (true)
{
boolean ii_hasnext = ii.hasNext();
boolean jj_hasnext = jj.hasNext();
if (ii_hasnext ^ jj_hasnext)
return false;
else if (ii_hasnext)
{
Object iiNext = ii.next();
Object jjNext = jj.next();
if (iiNext == jjNext)
continue;
else if (iiNext == null)
return false;
else if (!iiNext.equals(jjNext))
return false;
}
else return true;
}
}
public static ArrayList toArrayList(Iterator ii, int initial_capacity)
{
ArrayList out = new ArrayList(initial_capacity);
while (ii.hasNext())
out.add(ii.next());
return out;
}
/**
* Fills an array with the contents of an iterator. If the array is too small,
* it will contain the first portion of the iterator. If the array can contain
* more elements than the iterator, extra elements are left untouched, unless
* null_terminate is set to true, in which case the element immediately following
* the last from the iterator is set to null. (This method is intended to make
* it easy to implement Collection.toArray(Object[] oo) methods...
*
* @param null_terminate iff there is extra space in the array, set the element
* immediately after the last from the iterator to null.
*/
public static void fillArray(Iterator ii, Object[] fillMe, boolean null_terminate)
{
int i = 0;
int len = fillMe.length;
while ( i < len && ii.hasNext() )
fillMe[ i++ ] = ii.next();
if (null_terminate && i < len)
fillMe[i] = null;
}
public static void fillArray(Iterator ii, Object[] fillMe)
{ fillArray( ii, fillMe, false); }
/**
* @param null_terminate iff there is extra space in the array, set the element
* immediately after the last from the iterator to null.
*/
public static Object[] toArray(Iterator ii, int array_size, Class componentClass, boolean null_terminate)
{
Object[] out = (Object[]) Array.newInstance( componentClass, array_size );
fillArray(ii, out, null_terminate);
return out;
}
public static Object[] toArray(Iterator ii, int array_size, Class componentClass)
{ return toArray( ii, array_size, componentClass, false ); }
/**
* Designed to help implement Collection.toArray(Object[] )methods... does
* the right thing if you can express an iterator and know the size of your
* Collection.
*/
public static Object[] toArray(Iterator ii, int ii_size, Object[] maybeFillMe)
{
if (maybeFillMe.length >= ii_size)
{
fillArray( ii, maybeFillMe, true );
return maybeFillMe;
}
else
{
Class componentType = maybeFillMe.getClass().getComponentType();
return toArray( ii, ii_size, componentType );
}
}
private IteratorUtils()
{}
}
Protects an given iterator by preventing calls to remove().
/*
* JCommon : a free general purpose class library for the Java(tm) platform
*
*
* (C) Copyright 2000-2005, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jcommon/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ---------------------
* ReadOnlyIterator.java
* ---------------------
* (C)opyright 2003, 2004, by Thomas Morgner and Contributors.
*
* Original Author: Thomas Morgner;
* Contributor(s): -;
*
* $Id: ReadOnlyIterator.java,v 1.2 2005/10/18 13:24:19 mungady Exp $
*
* Changes
* -------------------------
* 18-Jul-2003 : Initial version
*
*/
import java.util.Iterator;
/**
* Protects an given iterator by preventing calls to remove().
*
* @author Thomas Morgner
*/
public class ReadOnlyIterator implements Iterator {
/** The base iterator which we protect. */
private Iterator base;
/**
* Creates a new read-only iterator for the given iterator.
*
* @param it the iterator.
*/
public ReadOnlyIterator(final Iterator it) {
if (it == null) {
throw new NullPointerException("Base iterator is null.");
}
this.base = it;
}
/**
* Returns <tt>true</tt> if the iteration has more elements. (In other
* words, returns <tt>true</tt> if <tt>next</tt> would return an element
* rather than throwing an exception.)
*
* @return <tt>true</tt> if the iterator has more elements.
*/
public boolean hasNext() {
return this.base.hasNext();
}
/**
* Returns the next element in the iteration.
* Throws NoSuchElementException when iteration has no more elements.
*
* @return the next element in the iteration.
*/
public Object next() {
return this.base.next();
}
/**
* Throws <code>UnsupportedOperationException</code>.
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
Remove an element from Collection using Java Iterator
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
for (String str: aList) {
System.out.println(str);
}
Iterator itr = aList.iterator();
// remove 2 from ArrayList using Iterator"s remove method.
String strElement = "";
while (itr.hasNext()) {
strElement = (String) itr.next();
if (strElement.equals("2")) {
itr.remove();
break;
}
}
for (String str: aList) {
System.out.println(str);
}
}
}
Returns an iterator over the children of the given element with the given tag name
import java.util.ArrayList;
import java.util.Iterator;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
* A utility class to cover up the rough bits of xml parsing
*
* @author
* @version $Revision: 2787 $
*/
@SuppressWarnings("unchecked")
public class XmlHelper {
/**
* Returns an iterator over the children of the given element with the given
* tag name.
*
* @param element
* The parent element
* @param tagName
* The name of the desired child
* @return An interator of children or null if element is null.
*/
public static Iterator getChildrenByTagName(Element element, String tagName) {
if (element == null)
return null;
// getElementsByTagName gives the corresponding elements in the whole
// descendance. We want only children
NodeList children = element.getChildNodes();
ArrayList goodChildren = new ArrayList();
for (int i = 0; i < children.getLength(); i++) {
Node currentChild = children.item(i);
if (currentChild.getNodeType() == Node.ELEMENT_NODE
&& ((Element) currentChild).getTagName().equals(tagName)) {
goodChildren.add(currentChild);
}
}
return goodChildren.iterator();
}
/**
* Gets the child of the specified element having the specified unique name.
* If there are more than one children elements with the same name and
* exception is thrown.
*
* @param element
* The parent element
* @param tagName
* The name of the desired child
* @return The named child.
*
* @throws Exception
* Child was not found or was not unique.
*/
public static Element getUniqueChild(Element element, String tagName) throws Exception {
Iterator goodChildren = getChildrenByTagName(element, tagName);
if (goodChildren != null && goodChildren.hasNext()) {
Element child = (Element) goodChildren.next();
if (goodChildren.hasNext()) {
throw new Exception("expected only one " + tagName + " tag");
}
return child;
} else {
throw new Exception("expected one " + tagName + " tag");
}
}
/**
* Gets the child of the specified element having the specified name. If the
* child with this name doesn"t exist then null is returned instead.
*
* @param element
* the parent element
* @param tagName
* the name of the desired child
* @return either the named child or null
* @throws Exception
*/
public static Element getOptionalChild(Element element, String tagName) throws Exception {
return getOptionalChild(element, tagName, null);
}
/**
* Gets the child of the specified element having the specified name. If the
* child with this name doesn"t exist then the supplied default element is
* returned instead.
*
* @param element
* the parent element
* @param tagName
* the name of the desired child
* @param defaultElement
* the element to return if the child doesn"t exist
* @return either the named child or the supplied default
* @throws Exception
*/
public static Element getOptionalChild(Element element, String tagName, Element defaultElement)
throws Exception {
Iterator goodChildren = getChildrenByTagName(element, tagName);
if (goodChildren != null && goodChildren.hasNext()) {
Element child = (Element) goodChildren.next();
if (goodChildren.hasNext()) {
throw new Exception("expected only one " + tagName + " tag");
}
return child;
} else {
return defaultElement;
}
}
/**
* Get the content of the given element.
*
* @param element
* The element to get the content for.
* @return The content of the element or null.
* @throws Exception
*/
public static String getElementContent(final Element element) throws Exception {
return getElementContent(element, null);
}
/**
* Get the content of the given element.
*
* @param element
* The element to get the content for.
* @param defaultStr
* The default to return when there is no content.
* @return The content of the element or the default.
* @throws Exception
*/
public static String getElementContent(Element element, String defaultStr) throws Exception {
if (element == null)
return defaultStr;
NodeList children = element.getChildNodes();
String result = "";
for (int i = 0; i < children.getLength(); i++) {
if (children.item(i).getNodeType() == Node.TEXT_NODE
|| children.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
result += children.item(i).getNodeValue();
} else if (children.item(i).getNodeType() == Node.ruMENT_NODE) {
// Ignore comment nodes
}
}
return result.trim();
}
/**
* Macro to get the content of a unique child element.
*
* @param element
* The parent element.
* @param tagName
* The name of the desired child.
* @return The element content or null.
* @throws Exception
*/
public static String getUniqueChildContent(Element element, String tagName) throws Exception {
return getElementContent(getUniqueChild(element, tagName));
}
/**
* Macro to get the content of an optional child element.
*
* @param element
* The parent element.
* @param tagName
* The name of the desired child.
* @return The element content or null.
* @throws Exception
*/
public static String getOptionalChildContent(Element element, String tagName) throws Exception {
return getElementContent(getOptionalChild(element, tagName));
}
public static boolean getOptionalChildBooleanContent(Element element, String name)
throws Exception {
Element child = getOptionalChild(element, name);
if (child != null) {
String value = getElementContent(child).toLowerCase();
return value.equals("true") || value.equals("yes");
}
return false;
}
}
Sorted Iterator
/**
*
* The ObjectStyle Group Software License, version 1.1
* ObjectStyle Group - http://objectstyle.org/
*
* Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
* of the software. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if any,
* must include the following acknowlegement:
* "This product includes software developed by independent contributors
* and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
* or promote products derived from this software without prior written
* permission. For written permission, email
* "andrus at objectstyle dot org".
*
* 5. Products derived from this software may not be called "ObjectStyle"
* or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
* names without prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS"" AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This software consists of voluntary contributions made by many
* individuals and hosted on ObjectStyle Group web site. For more
* information on the ObjectStyle Group, please see
* <http://objectstyle.org/>.
*/
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.Member;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.ruparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Contains various unorganized static utility methods used across Cayenne.
*
* @author Andrei Adamchik
*/
public class Util {
/**
* Returns a sorted iterator from an unsorted one. Use this method as a last resort,
* since it is much less efficient then just sorting a collection that backs the
* original iterator.
*/
public static Iterator sortedIterator(Iterator it, Comparator comparator) {
List list = new ArrayList();
while (it.hasNext()) {
list.add(it.next());
}
Collections.sort(list, comparator);
return list.iterator();
}
}
This constructs an Iterator over each day in a date range defined by a focus date and range style.
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.TimeZone;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A suite of utilities surrounding the use of the
* {@link java.util.Calendar} and {@link java.util.Date} object.
*
* DateUtils contains a lot of common methods considering manipulations
* of Dates or Calendars. Some methods require some extra explanation.
* The truncate and round methods could be considered the Math.floor(),
* Math.ceil() or Math.round versions for dates
* This way date-fields will be ignored in bottom-up order.
* As a complement to these methods we"ve introduced some fragment-methods.
* With these methods the Date-fields will be ignored in top-down order.
* Since a date without a year is not a valid date, you have to decide in what
* kind of date-field you want your result, for instance milliseconds or days.
*
*
*
*
* @author
* @author Phil Steitz
* @author Robert Scholte
* @since 2.0
* @version $Id: DateUtils.java 634096 2008-03-06 00:58:11Z niallp $
*/
public class Main {
/**
* The UTC time zone (often referred to as GMT).
*/
public static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("GMT");
/**
* Number of milliseconds in a standard second.
* @since 2.1
*/
public static final long MILLIS_PER_SECOND = 1000;
/**
* Number of milliseconds in a standard minute.
* @since 2.1
*/
public static final long MILLIS_PER_MINUTE = 60 * MILLIS_PER_SECOND;
/**
* Number of milliseconds in a standard hour.
* @since 2.1
*/
public static final long MILLIS_PER_HOUR = 60 * MILLIS_PER_MINUTE;
/**
* Number of milliseconds in a standard day.
* @since 2.1
*/
public static final long MILLIS_PER_DAY = 24 * MILLIS_PER_HOUR;
/**
* This is half a month, so this represents whether a date is in the top
* or bottom half of the month.
*/
public final static int SEMI_MONTH = 1001;
private static final int[][] fields = {
{Calendar.MILLISECOND},
{Calendar.SECOND},
{Calendar.MINUTE},
{Calendar.HOUR_OF_DAY, Calendar.HOUR},
{Calendar.DATE, Calendar.DAY_OF_MONTH, Calendar.AM_PM
/* Calendar.DAY_OF_YEAR, Calendar.DAY_OF_WEEK, Calendar.DAY_OF_WEEK_IN_MONTH */
},
{Calendar.MONTH, DateUtils.SEMI_MONTH},
{Calendar.YEAR},
{Calendar.ERA}};
/**
* A week range, starting on Sunday.
*/
public final static int RANGE_WEEK_SUNDAY = 1;
/**
* A week range, starting on Monday.
*/
public final static int RANGE_WEEK_MONDAY = 2;
/**
* A week range, starting on the day focused.
*/
public final static int RANGE_WEEK_RELATIVE = 3;
/**
* A week range, centered around the day focused.
*/
public final static int RANGE_WEEK_CENTER = 4;
/**
* A month range, the week starting on Sunday.
*/
public final static int RANGE_MONTH_SUNDAY = 5;
/**
* A month range, the week starting on Monday.
*/
public final static int RANGE_MONTH_MONDAY = 6;
//-----------------------------------------------------------------------
/**
* This constructs an <code>Iterator</code> over each day in a date
* range defined by a focus date and range style.
*
* For instance, passing Thursday, July 4, 2002 and a
* <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
* that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
* 2002, returning a Calendar instance for each intermediate day.
*
* This method provides an iterator that returns Calendar objects.
* The days are progressed using {@link Calendar#add(int, int)}.
*
* @param focus the date to work with, not null
* @param rangeStyle the style constant to use. Must be one of
* {@link DateUtils#RANGE_MONTH_SUNDAY},
* {@link DateUtils#RANGE_MONTH_MONDAY},
* {@link DateUtils#RANGE_WEEK_SUNDAY},
* {@link DateUtils#RANGE_WEEK_MONDAY},
* {@link DateUtils#RANGE_WEEK_RELATIVE},
* {@link DateUtils#RANGE_WEEK_CENTER}
* @return the date iterator, which always returns Calendar instances
* @throws IllegalArgumentException if the date is <code>null</code>
* @throws IllegalArgumentException if the rangeStyle is invalid
*/
public static Iterator iterator(Date focus, int rangeStyle) {
if (focus == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar gval = Calendar.getInstance();
gval.setTime(focus);
return iterator(gval, rangeStyle);
}
/**
* This constructs an <code>Iterator</code> over each day in a date
* range defined by a focus date and range style.
*
* For instance, passing Thursday, July 4, 2002 and a
* <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
* that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
* 2002, returning a Calendar instance for each intermediate day.
*
* This method provides an iterator that returns Calendar objects.
* The days are progressed using {@link Calendar#add(int, int)}.
*
* @param focus the date to work with
* @param rangeStyle the style constant to use. Must be one of
* {@link DateUtils#RANGE_MONTH_SUNDAY},
* {@link DateUtils#RANGE_MONTH_MONDAY},
* {@link DateUtils#RANGE_WEEK_SUNDAY},
* {@link DateUtils#RANGE_WEEK_MONDAY},
* {@link DateUtils#RANGE_WEEK_RELATIVE},
* {@link DateUtils#RANGE_WEEK_CENTER}
* @return the date iterator
* @throws IllegalArgumentException if the date is <code>null</code>
* @throws IllegalArgumentException if the rangeStyle is invalid
*/
public static Iterator iterator(Calendar focus, int rangeStyle) {
if (focus == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar start = null;
Calendar end = null;
int startCutoff = Calendar.SUNDAY;
int endCutoff = Calendar.SATURDAY;
switch (rangeStyle) {
case RANGE_MONTH_SUNDAY:
case RANGE_MONTH_MONDAY:
//Set start to the first of the month
start = truncate(focus, Calendar.MONTH);
//Set end to the last of the month
end = (Calendar) start.clone();
end.add(Calendar.MONTH, 1);
end.add(Calendar.DATE, -1);
//Loop start back to the previous sunday or monday
if (rangeStyle == RANGE_MONTH_MONDAY) {
startCutoff = Calendar.MONDAY;
endCutoff = Calendar.SUNDAY;
}
break;
case RANGE_WEEK_SUNDAY:
case RANGE_WEEK_MONDAY:
case RANGE_WEEK_RELATIVE:
case RANGE_WEEK_CENTER:
//Set start and end to the current date
start = truncate(focus, Calendar.DATE);
end = truncate(focus, Calendar.DATE);
switch (rangeStyle) {
case RANGE_WEEK_SUNDAY:
//already set by default
break;
case RANGE_WEEK_MONDAY:
startCutoff = Calendar.MONDAY;
endCutoff = Calendar.SUNDAY;
break;
case RANGE_WEEK_RELATIVE:
startCutoff = focus.get(Calendar.DAY_OF_WEEK);
endCutoff = startCutoff - 1;
break;
case RANGE_WEEK_CENTER:
startCutoff = focus.get(Calendar.DAY_OF_WEEK) - 3;
endCutoff = focus.get(Calendar.DAY_OF_WEEK) + 3;
break;
}
break;
default:
throw new IllegalArgumentException("The range style " + rangeStyle + " is not valid.");
}
if (startCutoff < Calendar.SUNDAY) {
startCutoff += 7;
}
if (startCutoff > Calendar.SATURDAY) {
startCutoff -= 7;
}
if (endCutoff < Calendar.SUNDAY) {
endCutoff += 7;
}
if (endCutoff > Calendar.SATURDAY) {
endCutoff -= 7;
}
while (start.get(Calendar.DAY_OF_WEEK) != startCutoff) {
start.add(Calendar.DATE, -1);
}
while (end.get(Calendar.DAY_OF_WEEK) != endCutoff) {
end.add(Calendar.DATE, 1);
}
return new DateIterator(start, end);
}
/**
* This constructs an <code>Iterator</code> over each day in a date
* range defined by a focus date and range style.
*
* For instance, passing Thursday, July 4, 2002 and a
* <code>RANGE_MONTH_SUNDAY</code> will return an <code>Iterator</code>
* that starts with Sunday, June 30, 2002 and ends with Saturday, August 3,
* 2002, returning a Calendar instance for each intermediate day.
*
* @param focus the date to work with, either
* <code>Date</code> or <code>Calendar</code>
* @param rangeStyle the style constant to use. Must be one of the range
* styles listed for the {@link #iterator(Calendar, int)} method.
* @return the date iterator
* @throws IllegalArgumentException if the date
* is <code>null</code>
* @throws ClassCastException if the object type is
* not a <code>Date</code> or <code>Calendar</code>
*/
public static Iterator iterator(Object focus, int rangeStyle) {
if (focus == null) {
throw new IllegalArgumentException("The date must not be null");
}
if (focus instanceof Date) {
return iterator((Date) focus, rangeStyle);
} else if (focus instanceof Calendar) {
return iterator((Calendar) focus, rangeStyle);
} else {
throw new ClassCastException("Could not iterate based on " + focus);
}
}
/**
* Truncate this date, leaving the field specified as the most
* significant field.
*
* For example, if you had the datetime of 28 Mar 2002
* 13:45:01.231, if you passed with HOUR, it would return 28 Mar
* 2002 13:00:00.000. If this was passed with MONTH, it would
* return 1 Mar 2002 0:00:00.000.
*
* @param date the date to work with, either <code>Date</code>
* or <code>Calendar</code>
* @param field the field from <code>Calendar</code>
* or <code>SEMI_MONTH</code>
* @return the rounded date
* @throws IllegalArgumentException if the date
* is <code>null</code>
* @throws ClassCastException if the object type is not a
* <code>Date</code> or <code>Calendar</code>
* @throws ArithmeticException if the year is over 280 million
*/
public static Date truncate(Object date, int field) {
if (date == null) {
throw new IllegalArgumentException("The date must not be null");
}
if (date instanceof Date) {
return truncate((Date) date, field);
} else if (date instanceof Calendar) {
return truncate((Calendar) date, field).getTime();
} else {
throw new ClassCastException("Could not truncate " + date);
}
}
/**
* Truncate this date, leaving the field specified as the most
* significant field.
*
* For example, if you had the datetime of 28 Mar 2002
* 13:45:01.231, if you passed with HOUR, it would return 28 Mar
* 2002 13:00:00.000. If this was passed with MONTH, it would
* return 1 Mar 2002 0:00:00.000.
*
* @param date the date to work with
* @param field the field from <code>Calendar</code>
* or <code>SEMI_MONTH</code>
* @return the rounded date (a different object)
* @throws IllegalArgumentException if the date is <code>null</code>
* @throws ArithmeticException if the year is over 280 million
*/
public static Calendar truncate(Calendar date, int field) {
if (date == null) {
throw new IllegalArgumentException("The date must not be null");
}
Calendar truncated = (Calendar) date.clone();
modify(truncated, field, false);
return truncated;
}
//-----------------------------------------------------------------------
/**
* Internal calculation method.
*
* @param val the calendar
* @param field the field constant
* @param round true to round, false to truncate
* @throws ArithmeticException if the year is over 280 million
*/
private static void modify(Calendar val, int field, boolean round) {
if (val.get(Calendar.YEAR) > 280000000) {
throw new ArithmeticException("Calendar value too large for accurate calculations");
}
if (field == Calendar.MILLISECOND) {
return;
}
// ----------------- Fix for LANG-59 ---------------------- START ---------------
// see http://issues.apache.org/jira/browse/LANG-59
//
// Manually truncate milliseconds, seconds and minutes, rather than using
// Calendar methods.
Date date = val.getTime();
long time = date.getTime();
boolean done = false;
// truncate milliseconds
int millisecs = val.get(Calendar.MILLISECOND);
if (!round || millisecs < 500) {
time = time - millisecs;
}
if (field == Calendar.SECOND) {
done = true;
}
// truncate seconds
int seconds = val.get(Calendar.SECOND);
if (!done && (!round || seconds < 30)) {
time = time - (seconds * 1000L);
}
if (field == Calendar.MINUTE) {
done = true;
}
// truncate minutes
int minutes = val.get(Calendar.MINUTE);
if (!done && (!round || minutes < 30)) {
time = time - (minutes * 60000L);
}
// reset time
if (date.getTime() != time) {
date.setTime(time);
val.setTime(date);
}
// ----------------- Fix for LANG-59 ----------------------- END ----------------
boolean roundUp = false;
for (int i = 0; i < fields.length; i++) {
for (int j = 0; j < fields[i].length; j++) {
if (fields[i][j] == field) {
//This is our field... we stop looping
if (round && roundUp) {
if (field == DateUtils.SEMI_MONTH) {
//This is a special case that"s hard to generalize
//If the date is 1, we round up to 16, otherwise
// we subtract 15 days and add 1 month
if (val.get(Calendar.DATE) == 1) {
val.add(Calendar.DATE, 15);
} else {
val.add(Calendar.DATE, -15);
val.add(Calendar.MONTH, 1);
}
} else {
//We need at add one to this field since the
// last number causes us to round up
val.add(fields[i][0], 1);
}
}
return;
}
}
//We have various fields that are not easy roundings
int offset = 0;
boolean offsetSet = false;
//These are special types of fields that require different rounding rules
switch (field) {
case DateUtils.SEMI_MONTH:
if (fields[i][0] == Calendar.DATE) {
//If we"re going to drop the DATE field"s value,
// we want to do this our own way.
//We need to subtrace 1 since the date has a minimum of 1
offset = val.get(Calendar.DATE) - 1;
//If we"re above 15 days adjustment, that means we"re in the
// bottom half of the month and should stay accordingly.
if (offset >= 15) {
offset -= 15;
}
//Record whether we"re in the top or bottom half of that range
roundUp = offset > 7;
offsetSet = true;
}
break;
case Calendar.AM_PM:
if (fields[i][0] == Calendar.HOUR_OF_DAY) {
//If we"re going to drop the HOUR field"s value,
// we want to do this our own way.
offset = val.get(Calendar.HOUR_OF_DAY);
if (offset >= 12) {
offset -= 12;
}
roundUp = offset > 6;
offsetSet = true;
}
break;
}
if (!offsetSet) {
int min = val.getActualMinimum(fields[i][0]);
int max = val.getActualMaximum(fields[i][0]);
//Calculate the offset from the minimum allowed value
offset = val.get(fields[i][0]) - min;
//Set roundUp if this is more than half way between the minimum and maximum
roundUp = offset > ((max - min) / 2);
}
//We need to remove this field
if (offset != 0) {
val.set(fields[i][0], val.get(fields[i][0]) - offset);
}
}
throw new IllegalArgumentException("The field " + field + " is not supported");
}
/**
* Date iterator.
*/
static class DateIterator implements Iterator {
private final Calendar endFinal;
private final Calendar spot;
/**
* Constructs a DateIterator that ranges from one date to another.
*
* @param startFinal start date (inclusive)
* @param endFinal end date (not inclusive)
*/
DateIterator(Calendar startFinal, Calendar endFinal) {
super();
this.endFinal = endFinal;
spot = startFinal;
spot.add(Calendar.DATE, -1);
}
/**
* Has the iterator not reached the end date yet?
*
* @return <code>true</code> if the iterator has yet to reach the end date
*/
public boolean hasNext() {
return spot.before(endFinal);
}
/**
* Return the next calendar in the iteration
*
* @return Object calendar for the next date
*/
public Object next() {
if (spot.equals(endFinal)) {
throw new RuntimeException();
}
spot.add(Calendar.DATE, 1);
return spot.clone();
}
/**
* Always throws UnsupportedOperationException.
*
* @throws UnsupportedOperationException
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
}
}
Traverse through ArrayList in forward direction using Java ListIterator
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
ListIterator listIterator = aList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
}
}
Traverse through ArrayList in reverse direction using Java ListIterator
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {
public static void main(String[] args) {
ArrayList<String> aList = new ArrayList<String>();
aList.add("1");
aList.add("2");
aList.add("3");
aList.add("4");
aList.add("5");
ListIterator<String> listIterator = aList.listIterator();
while (listIterator.hasNext()){
System.out.println(listIterator.next());
}
while (listIterator.hasPrevious()){
System.out.println(listIterator.previous());
}
}
}
Treat an Iterator as an Iterable
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
import java.io.Serializable;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* @since 4.37
* @author Jaroslav Tulach
*/
public class Utils {
/**
* Treat an {@link Iterator} as an {@link Iterable} so it can be used in an enhanced for-loop.
* Bear in mind that the iterator is "consumed" by the loop and so should be used only once.
* Generally it is best to put the code which obtains the iterator inside the loop header.
* <div class="nonnormative">
* Example of correct usage:
* <pre>
* String text = ...;
* for (String token : NbCollections.iterable(new {@link java.util.Scanner}(text))) {
* // ...
* }
* </pre>
* </div>
* @param iterator an iterator
* @return an iterable wrapper which will traverse the iterator once
* @throws NullPointerException if the iterator is null
* @see
* @since org.openide.util 7.5
*/
public static <E> Iterable<E> iterable(final Iterator<E> iterator) {
if (iterator == null) {
throw new NullPointerException();
}
return new Iterable<E>() {
public Iterator<E> iterator() {
return iterator;
}
};
}
}
Use an Iterator to cycle through a collection in the forward direction.
// Use a ListIterator to cycle through a collection in the reverse direction.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
class Employee {
String name;
String number;
Employee(String n, String num) {
name = n;
number = num;
}
}
public class Main {
public static void main(String args[]) {
LinkedList<Employee> phonelist = new LinkedList<Employee>();
phonelist.add(new Employee("A", "1"));
phonelist.add(new Employee("B", "2"));
phonelist.add(new Employee("C", "3"));
Iterator<Employee> itr = phonelist.iterator();
Employee pe;
while (itr.hasNext()) {
pe = itr.next();
System.out.println(pe.name + ": " + pe.number);
}
ListIterator<Employee> litr = phonelist.listIterator(phonelist.size());
while (litr.hasPrevious()) {
pe = litr.previous();
System.out.println(pe.name + ": " + pe.number);
}
}
}
Use Iterator to loop through ArrayList
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
al.add(new Integer(5));
al.add(new Integer(6));
al.add(new Integer(7));
al.add(new Integer(8));
al.add(new Integer(9));
al.add(new Integer(10));
al.set(5, new Integer(66));
for (Iterator i = al.iterator(); i.hasNext();) {
Integer integer = (Integer) i.next();
System.out.println(integer);
}
}
}
Use Iterator to loop through the HashMap class
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map errors = new HashMap();
errors.put("404", "A.");
errors.put("403", "B.");
errors.put("500", "C.");
String errorDesc = (String) errors.get("404");
System.out.println("Error 404: " + errorDesc);
Iterator iterator = errors.keySet().iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println("Error " + key + " means " + errors.get(key));
}
}
}