Search code examples
javaswingjcombobox

How to avoid duplicate values in a JComboBox?


enter image description here

cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Iterator i = products.entrySet().iterator();
while (i.hasNext())
{
    Map.Entry me = (Map.Entry) i.next();
    Product p = (Product) me.getValue();

    if(!p.getMake().equals(cmbMake.getSelectedItem()))
    {
        cmbMake.addItem("" + p.getMake());
    }
}

I have a class which holds product details is there anyway to stop the same make being added to the combo box?


Solution

  • You can try this code (I added some code to yours). The code gets the values of makes and stores them in a Set collection, and then populates the combo box.

    cmbMake = new JComboBox();
    cmbMake.addItem("**Please Select**");
    
    Iterator i = products.entrySet().iterator();
    Set<String> uniqueMakes = new HashSet<>(); // this stores unique makes
    
    while (i.hasNext())
    {
        Map.Entry me = (Map.Entry) i.next();
        Product p = (Product) me.getValue();
    
        //if(! p.getMake().equals(cmbMake.getSelectedItem()))
        //{
        //  cmbMake.addItem("" + p.getMake());
        //}
    
        uniqueMakes.add(p.getMake());
    }
    
    System.out.println(uniqueMakes); // this prints the makes
    
    // Add makes to the combo box
    for (String make : uniqueMakes) {
        cmbMake.addItem(make);
    }
    


    Suggestions: You can use type parameters while using some of these, for example:

    JComboBox<String> cmbMake = new JComboBox<>();
    Iterator<Product> i = products.entrySet().iterator();
    

    EDIT: Here are tutorials on using Set collection and using Generics.

    EDIT (another way of coding the same functionality using functional-style programming):

    cmbMake = new JComboBox<String>();
    cmbMake.addItem("**Please Select**");
    products.values()
            .map(product -> product.getMake())
            .collect(Collectors.toCollection(HashSet::new))
            .forEach(make -> cmbMake.addItem(make));