How to add only unique values from CSV into ComboBox?

a 夏天 提交于 2019-12-02 05:08:35

Try putting all the words in a Set first and then add it in the combobox. Set itself will take care of exact one occurrence of each word.

Something like this:

    while ((line = br.readLine()) != null) {

        // use comma as separator

        String[] bookingdata = line.split(cvsSplitBy);

        location = bookingdata[1];
        ComboBoxModel model = cmb1.getModel();
        int size = model.getSize();
        // add all location in set and set will only allow distinct values
        locationSet.add(location);

       }
       // after looping through all location put it in combobox
       for(String location:locationSet)cmb1.addItem(location);
   }
  }

As discussed in comments, Sets are meant to keep unique values. Please find the screenshot of JShell below:

PS: This is just to give an idea and may need some amendment as per requirement.

--EDITED--

As discussed, it seems you are still missing something, I tried and write below piece of code and worked fine

package com.digital.core;

import java.util.HashSet;
import java.util.Set;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Test {

    public static void main(String[] args) {
       JFrame jframe = new JFrame();
       jframe.setSize(300, 300);
       String data = "id,from,\n" + 
            "1,Jakarta\n" + 
            "2,Jakarta\n" + 
            "5,Jakarta\n" + 
            "6,Jakarta\n" + 
            "10,Bandung\n" + 
            "11,Bandung\n" + 
            "12,Bandung";
       String[] dataArr = data.split("\n");

       Set<String> locationSet = new HashSet<>();
       for(String line:dataArr) {
           locationSet.add(line.split(",")[1]);
       }
       JComboBox<String> comboBox = new JComboBox<>();
       for(String location:locationSet)
       comboBox.addItem(location);
       jframe.add(comboBox);
       jframe.setVisible(true);


    }


}

You could create an ObservablArrayList of strings and as you read the CSV file, check if the list already contains that string:

    ObservableList<String> locationsList = FXCollections.observableArrayList();

    // Add your strings to the array as they're loaded, but check to 
    // make sure the string does not already exist
    if (!locationsList.contains(location)) {
        locationsList.add(location);
    }

Then, after reading the whole file and populating the list, just set the items in your combobox to that ObservableArrayList.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!