将hashmap的字符串值添加到JComboBox

时间:2016-01-18 19:17:15

标签: java

我是一个Java新手,我想从不同的类中获取所有使用hashmap填充我的JComboBox的值

 public class StockData {

private static class Item {

    Item(String n, double p, int q) {
        name = n;
        price = p;
        quantity = q;
    }

    // get methods
    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getQuantity() {
        return quantity;
    }

    // instance variables 
    private final String name;
    private final double price;
    private int quantity;
}

// with a Map you use put to insert a key, value pair 
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private final static Map<String, Item> stock = new HashMap();

static {
    // if you want to have extra stock items, put them in here
    // use the same style - keys should be Strings
    stock.put("00", new Item("Bath towel", 5.50, 10));
    stock.put("11", new Item("Plebney light", 20.00, 5));
    stock.put("22", new Item("Gorilla suit", 30.00, 7));
    stock.put("33", new Item("Whizz games console", 50.00, 8));
    stock.put("44", new Item("Oven", 200.00, 4));
}
public static Map<String, Item> getStock() {
    return stock;
   }
public static String getName(String key) {
    Item item = stock.get(key);
    if (item == null) {
        return null; // null means no such item
    } else {
        return item.getName();
    }
}
}

我想在我的JCombobox中放置所有这些价值,如浴巾,Plebney灯等。

  package stock;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class PurchaseItem extends JFrame implements ActionListener {
   // StockData ss = new StockData();
       JComboBox<String> box = new JComboBox<>(stock.values().stream().map(Item::getName).toArray(String[]::new));
JComboBox b = new JComboBox();
}

1 个答案:

答案 0 :(得分:1)

假设您的Item对象具有getName函数,您可以写下:

    JComboBox<String> box = new JComboBox<>(
        stock.values().stream()
        .map(Item::getName)
        .toArray(String[]::new)
    );

我认为理解语法的最佳方法是让你去阅读调用的方法的javadoc。还有一个小的解释.values()返回一组股票地图中的所有值然后流,因为文档说返回一个顺序流,集合作为源,然后map calles getName()函数(我假设你有:public String getName())为流中的每个对象,然后将所有字符串转换为字符串数组。结果与:

相同
    JComboBox<String> box = new JComboBox<>();
        for(Item item:stock.values()){
            box.addItem(item.getName());
        }

编辑:

如果stock变量在不同的类中,那么PurchaseItem比PurchaseItem看不到它。您可以通过更改隐私或为其创建get函数来使其暴露:

   public static Map<String, Item> getStock() {
    return stock;
   }

因为我最初给你写的这个函数你需要这些vlaues你可以为这样的vlaue集合做一个getter:

public static Collection<Item> getStock() {
    return stock.values();
}

然后修改这样的代码:

JComboBox<String> box = new JComboBox<>(
        NameOfTheClassWhichContainsStock.getStock().stream()
        .map(Item::getName)
        .toArray(String[]::new)
);

EDIT2: 您的Item类是私有的,因此它在StockData类之外是不可见的,这就是无法找到它的原因。如果将Item类更改为public并在PurchaseItem类中导入StockData,则可以编写:

JComboBox<String> box = new JComboBox<>(StockData.getStock()
    .values()
    .stream()
    .map(StockData.Item::getName)
    .toArray(String[]::new)
);

EDIT3:在我的电脑上声明:

package stockdata;

import java.util.HashMap;
import java.util.Map;

public class StockData {

public static class Item {

    Item(String n, double p, int q) {
        name = n;
        price = p;
        quantity = q;
    }

    // get methods
    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getQuantity() {
        return quantity;
    }

    // instance variables
    private final String name;
    private final double price;
    private int quantity;
}

// with a Map you use put to insert a key, value pair
// and get(key) to retrieve the value associated with a key
// You don't need to understand how this works!
private final static Map<String, Item> stock = new HashMap<>();

static {
    // if you want to have extra stock items, put them in here
    // use the same style - keys should be Strings
    stock.put("00", new Item("Bath towel", 5.50, 10));
    stock.put("11", new Item("Plebney light", 20.00, 5));
    stock.put("22", new Item("Gorilla suit", 30.00, 7));
    stock.put("33", new Item("Whizz games console", 50.00, 8));
    stock.put("44", new Item("Oven", 200.00, 4));
}

public static Map<String, Item> getStock() {
    return stock;
}

public static String getName(String key) {
    Item item = stock.get(key);
    if (item == null) {
        return null; // null means no such item
    } else {
        return item.getName();
    }
}
}

// ============================================= ====================

package stockdata;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import stockdata.StockData;

public class PurchaseItem extends JFrame implements ActionListener {
    // StockData ss = new StockData();
    JComboBox<String> box = new JComboBox<>(StockData.getStock().values().stream().map(StockData.Item::getName).toArray(String[]::new));
    JComboBox b = new JComboBox();

    @Override
    public void actionPerformed(ActionEvent arg0) {
        // TODO Auto-generated method stub

    }
}

EDIT4:

public double getPriceForName(String itemName){

    return StockData.getStock()
            .values()
            .stream()
            .filter(item->item.getName().equals(itemName))//filter only those whit the given name
            .mapToDouble(StockData.Item::getPrice)//get item price
            .findFirst()//Item name should be unique then it is ok to do this
            .getAsDouble();//if there is no item with the given name this will throw a NoSuchElementException
}

public int getQuantityForName(String itemName){

    return StockData.getStock()
            .values()
            .stream()
            .filter(item->item.getName().equals(itemName))//filter only those whit the given name
            .mapToInt(StockData.Item::getQuantity)//get item quantity
            .findFirst()//Item name should be unique then it is ok to do this
            .getAsInt();//if there is no item with the given name this will throw a NoSuchElementException
}