Iterating Over a Map - Java Collection Framework

Java examples for Collection Framework:Iterable

Description

Iterating Over a Map

Demo Code

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class Main implements Iterable<Stock> {

  Map<String, Stock> portfolio = new HashMap<>();

  public void add(Stock stock) {
    portfolio.put(stock.getSymbol(), stock);
  }/*  www  . j  av a2s  .c o  m*/

  public void add(List<Stock> stocks) {
    for (Stock s : stocks) {
      portfolio.put(s.getSymbol(), s);
    }
  }

  @Override
  public Iterator<Stock> iterator() {
    return portfolio.values().iterator();
  }

  public static void main(String[] args) {

    Main myPortfolio = new Main();
    myPortfolio.add(new Stock("ORCL", "Oracle", 500.0));
    myPortfolio.add(new Stock("AAPL", "Apple", 200.0));
    myPortfolio.add(new Stock("GOOG", "Google", 100.0));
    myPortfolio.add(new Stock("IBM", "IBM", 50.0));
    myPortfolio.add(new Stock("MCD", "McDonalds", 300.0));

    // foreach loop (uses Iterator returned from iterator() method)
    for (Stock stock : myPortfolio) {
      System.out.println(stock);
    }

    myPortfolio.forEach((stock) -> System.out.println(stock));

  }
}

class Stock {
  private String symbol;
  private String name;
  private double shares;

  public Stock(String symbol, String name, double shares) {
    this.symbol = symbol;
    this.name = name;
    this.shares = shares;
  }

  public String getSymbol() {
    return symbol;
  }

  public String getName() {
    return name;
  }

  public double getShares() {
    return shares;
  }

  public String toString() {
    return shares + " shares of " + symbol + " (" + name + ")";
  }
}

Result


Related Tutorials