Java/Language Basics/Foreach

Материал из Java эксперт
Версия от 06:47, 1 июня 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Foreach and generic data structure

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
import java.util.Collection;
import java.util.List;
import java.util.ArrayList;
public class ForeachDemo {
  static void iterate(Collection<String> c) {
      for (String s : c)
      System.out.println(s);
  }
  public static void main(String args[]) {
    List<String> l = new ArrayList<String>();
    l.add("Toronto");
    l.add("Stockholm");
    iterate(l);
  }
}





Foreach Array

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
public class ForeachArray {
  public static void main(String args[]) {
    String[] data = { "Toronto", "Stockholm" };
    for (String s : data) {
      System.out.println(s);
    }
  }
}





Java for in (forin): line-by-line iteration through a text file

/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.util.Iterator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
/**
 * This class allows line-by-line iteration through a text file.
 * The iterator"s remove() method throws UnsupportedOperatorException.
 * The iterator wraps and rethrows IOExceptions as IllegalArgumentExceptions.
 */
public class TextFile implements Iterable<String> {
  // Used by the TextFileIterator class below
  final String filename;
  public TextFile(String filename) { 
    this.filename = filename; 
  }
  // This is the one method of the Iterable interface
  public Iterator<String> iterator() { 
    return new TextFileIterator(); 
  }

  // This non-static member class is the iterator implementation
  class TextFileIterator implements Iterator<String> {
    // The stream we"re reading from
    BufferedReader in;
    // Return value of next call to next()
    String nextline;
    public TextFileIterator() {
      // Open the file and read and remember the first line.
      // We peek ahead like this for the benefit of hasNext().
      try {
        in = new BufferedReader(new FileReader(filename));
        nextline = in.readLine();
      } catch(IOException e) { 
        throw new IllegalArgumentException(e); 
      }
    }
    // If the next line is non-null, then we have a next line
    public boolean hasNext() { 
      return nextline != null; 
    }
    // Return the next line, but first read the line that follows it.
    public String next() {
      try {
        String result = nextline;
        // If we haven"t reached EOF yet
        if (nextline != null) {  
          nextline = in.readLine(); // Read another line
          if (nextline == null) 
            in.close();             // And close on EOF
        }
        // Return the line we read last time through.
        return result;
      } catch(IOException e) { 
        throw new IllegalArgumentException(e); 
      }
    }
    // The file is read-only; we don"t allow lines to be removed.
    public void remove() { 
      throw new UnsupportedOperationException(); 
    }
  }
  public static void main(String[] args) {
    String filename = "TextFile.java";
    if (args.length > 0) 
      filename = args[0];
    for(String line : new TextFile(filename))
      System.out.println(line);
  }
}





Java for In(forin) Tester

/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class ForInTester {
  public ForInTester() {
  }
  public List getList() {
    List list = new LinkedList();
    for (int i = 1; i <= 100; i++) {
      list.add("Item " + i);
    }
    return list;
  }
  /**
   * <p>Test a very basic, pre-Java 1.5 for loop</p>
   */
  public void testForLoop(PrintStream out) throws IOException {
    List list = getList(); // initialize this list elsewhere
    for (Iterator i = list.iterator(); i.hasNext(); ) {
      Object listElement = i.next();
      out.println(listElement.toString());
      // Do something else with this list object
    }
  }
  /**
   * <p>Test a very basic, Java 1.5 for/in loop</p>
   */
  public void testForInLoop(PrintStream out) throws IOException {
    List list = getList(); // initialize this list elsewhere
    for (Object listElement : list) {
      out.println(listElement.toString());
      // Do something else with this list object
    }
  }
  /**
   * <p>Test a simple array iteration</p>
   */
  public void testArrayLooping(PrintStream out) throws IOException {
    int[] primes = new int[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 };
    
    // Print the primes out using a for/in loop
    for (int n : primes) {
      out.println(n);
    }
  }
  /**
   * <p>Test an object array iteration</p>
   */
  public void testObjectArrayLooping(PrintStream out) throws IOException {
    List[] list_array = new List[3];
    list_array[0] = getList();
    list_array[1] = getList();
    list_array[2] = getList();
    for (List l : list_array) {
      out.println(l.getClass().getName());
    }
  }
  /**
   * <p>Show list position in a loop (not possible with for/in)</p>
   */
  public void determineListPosition(PrintStream out, String[] args) 
    throws IOException {
    List<String> wordList = new LinkedList<String>();
    // Impossible to assign the words, since the iterator is used
    for (int i=0; i<args.length; i++) {
      wordList.add("word " + (i+1) + ": "" + args[i] + """);
    }
    // You can print the words using for/in, but not assign them
    for (String word : wordList) {
      out.println(word);
    }
    StringBuffer longList = new StringBuffer();
    for (int i = 0, len=wordList.size(); i < len; i++) {
      if (i < (len-1)) {
        longList.append(wordList.get(i))
                .append(", ");
      } else {
        longList.append(wordList.get(i));
      }
    }
    out.println(longList);
  }
  /**
   * <p>for/in can"t remove items using an Iterator</p>
   */
  public void removeListItems(PrintStream out, String[] args) 
    throws IOException {
    List<String> wordList = new LinkedList<String>();
    // Assign some words
    for (int i=0; i<args.length; i++) {
      wordList.add("word " + (i+1) + ": "" + args[i] + """);
    }
    // Remove all words with "1" in them. Impossible with for/in
    for (Iterator i = wordList.iterator(); i.hasNext(); ) {
      String word = (String)i.next();
      if (word.indexOf("1") != -1) {
        i.remove();
      }
    }
    // You can print the words using for/in
    for (String word : wordList) {
      out.println(word);
    }
  }
  public static void main(String[] args) {
    try {
      String[] s = new String[]{"a","b","c"};
      
      
      
      ForInTester tester = new ForInTester();
      tester.testForLoop(System.out);
      tester.testForInLoop(System.out);
      tester.testArrayLooping(System.out);
      tester.testObjectArrayLooping(System.out);
      tester.determineListPosition(System.out, s);
      tester.removeListItems(System.out, s);
      
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}





Java for in (forin) with Collection

/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ForInDemo {
  public static void main(String[] args) {
    // These are collections we"ll iterate over below.
    List wordlist = new ArrayList();
    Set wordset = new HashSet();
    // We start with a basic loop over the elements of an array.
    // The body of the loop is executed once for each element of args[].
    // Each time through one element is assigned to the variable word.
    System.out.println("Assigning arguments to lists...");
    for(String word : args) {
      System.out.print(word + " ");
      wordlist.add(word);
      wordset.add(word);
    }
    System.out.println();
    // Iterate through the elements of the List now.
    // Since lists have an order, these words should appear as above
    System.out.println("Printing words from wordlist " +
      "(ordered, with duplicates)...");
    for(Object word : wordlist) {
      System.out.print((String)word + " ");
    }
    System.out.println();
    // Do the same for the Set. The loop looks the same but by virtue of
    // using a Set, we lose the word order and also discard duplicates.
    System.out.println("Printing words from wordset " +
      "(unordered, no duplicates)...");
    for(Object word : wordset) {
      System.out.print((String)word + " ");
    }
  }
}





Java for in (forin) with generic Collection

/*
License for Java 1.5 "Tiger": A Developer"s Notebook
     (O"Reilly) example package
Java 1.5 "Tiger": A Developer"s Notebook (O"Reilly) 
by Brett McLaughlin and David Flanagan.
ISBN: 0-596-00738-8
You can use the examples and the source code any way you want, but
please include a reference to where it comes from if you use it in
your own products or services. Also note that this software is
provided by the author "as is", with no expressed or implied warranties. 
In no event shall the author be liable for any direct or indirect
damages arising in any way out of the use of this software.
*/

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ForInGenericsDemo {
  public static void main(String[] args) {
    // These are collections we"ll iterate over below.
    List<String> wordlist = new ArrayList<String>();
    Set<String> wordset = new HashSet<String>();
    // We start with a basic loop over the elements of an array.
    // The body of the loop is executed once for each element of args[].
    // Each time through one element is assigned to the variable word.
    System.out.println("Assigning arguments to lists...");
    for(String word : args) {
      System.out.print(word + " ");
      wordlist.add(word);
      wordset.add(word);
    }
    System.out.println();
    // Iterate through the elements of the List now.
    // Since lists have an order, these words should appear as above
    System.out.println("Printing words from wordlist " +
      "(ordered, with duplicates)...");
    for(String word : wordlist) {
      System.out.print(word + " ");
    }
    System.out.println();
    // Do the same for the Set. The loop looks the same but by virtue of
    // using a Set, we lose the word order and also discard duplicates.
    System.out.println("Printing words from wordset " +
      "(unordered, no duplicates)...");
    for(String word : wordset) {
      System.out.print(word + " ");
    }
  }
}





Search an array using foreach(for each) style for.

 
public class MainClass {
  public static void main(String args[]) {
    int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
    int val = 5;
    boolean found = false;
    for (int x : nums) {
      if (x == val) {
        found = true;
        break;
      }
    }
    if (found)
      System.out.println("Value found!");
  }
}





Simple demo to print all the types of an enum

/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/** Simple demo to print all the types of an enum. */
public class EnumList {
  enum State { ON, OFF, UNKNOWN };
  
  public static void main(String[] args) {
    for (State i : State.values()) {
      System.out.println(i);
    }
  }
}





The foreach(for each) loop is essentially read-only.

public class MainClass {
  public static void main(String args[]) {
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    for (int x : nums) {
      System.out.print(x + " ");
      x = x * 10; // no effect on nums
    }
    System.out.println();
    for (int x : nums)
      System.out.print(x + " ");
    System.out.println();
  }
}





Use a foreach(for each) style for loop.

public class ForEach {  
  public static void main(String args[]) {  
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
    int sum = 0;  
 
    // use for-each style for to display and sum the values 
    for(int x : nums) {  
      System.out.println("Value is: " + x); 
      sum += x;  
    }  
 
    System.out.println("Summation: " + sum); 
  }  
}





Use break with a foreach(for each) style for.

public class ForEach2 {  
  public static void main(String args[]) {  
    int sum = 0;  
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  
 
    // Use for to display and sum the values. 
    for(int x : nums) {  
      System.out.println("Value is: " + x);  
      sum += x;  
      if(x == 5) break; // stop the loop when 5 is obtained  
    }  
    System.out.println("Summation of first 5 elements: " + sum);  
  }  
}





Use foreach(for each) style for on a two-dimensional array.

public class MainClass {
  public static void main(String args[]) {
    int sum = 0;
    int nums[][] = new int[3][5];
    for (int i = 0; i < 3; i++)
      for (int j = 0; j < 5; j++)
        nums[i][j] = (i + 1) * (j + 1);
    for (int x[] : nums) {
      for (int y : x) {
        System.out.println("Value is: " + y);
        sum += y;
      }
    }
    System.out.println("Summation: " + sum);
  }
}





Using a foreach(for each) for loop on an Iterable object.

import java.util.*; 
 
class StrIterable implements Iterable<Character>, 
                             Iterator<Character> { 
  private String str; 
  private int count = 0; 
 
  StrIterable(String s) { 
    str = s; 
  } 
 
  // The next three methods impement Iterator. 
  public boolean hasNext() { 
    if(count < str.length()) return true; 
    return false; 
  } 
 
  public Character next() { 
    if(count == str.length())  
      throw new NoSuchElementException(); 
 
    count++; 
    return str.charAt(count-1); 
  } 
 
  public void remove() { 
    throw new UnsupportedOperationException(); 
  } 
 
  // This method implements Iterable. 
  public Iterator<Character> iterator() { 
    return this; 
  } 
} 
 
public class MainClass {  
  public static void main(String args[]) {  
    StrIterable x = new StrIterable("This is a test."); 
 
    for(char ch : x) 
      System.out.print(ch); 
 
    System.out.println(); 
  }  
}





Using a foreach(for each) for loop with a collection.

import java.util.ArrayList;
public class MainClass {
  static double getAvg(ArrayList<Double> nums) {
    double sum = 0.0;
    for (double itr : nums)
      sum = sum + itr;
    return sum / nums.size();
  }
  public static void main(String args[]) {
    ArrayList<Double> list = new ArrayList<Double>();
    list.add(10.14);
    list.add(20.22);
    list.add(30.78);
    list.add(40.46);
    double avg = getAvg(list);
    System.out.println("List average is " + avg);
  }
}