集册 Java实例教程 遍历地图

遍历地图

欢马劈雪     最近更新时间:2020-01-02 10:19:05

616
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
在地图上迭代

import java.util.HashMap;

import java.util.Iterator;// 来自 时代Java

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);

  }


  public void add(List<Stock> stocks) {

    for (Stock s : stocks) {

      portfolio.put(s.getSymbol(), s);//n o w j a v a . c o m - 时  代  Java 提 供

    }

  }


  @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() {

    
展开阅读全文