How to add only unique values from CSV into ComboBox?

浪子不回头ぞ 提交于 2019-12-02 09:32:02

问题


I want to read a csv File and put words " Jakarta " and " Bandung " in a combobox. Here's the input

id,from,
1,Jakarta
2,Jakarta
5,Jakarta
6,Jakarta
10,Bandung
11,Bandung
12,Bandung

I managed to get the words and put it in the combobox, but as you can see, the text file itself contains a lot word " Jakarta " and " Bandung " while i want to show both only once in the combobox.

Here's my temporary code, which works for now but inefficient and probably can't be used if the word has more variety

public String location;

private void formWindowOpened(java.awt.event.WindowEvent evt) {

    String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
    BufferedReader br = null;
    LineNumberReader reader = null;
    String line = "";
    String cvsSplitBy = "-|\\,";

        br = new BufferedReader(new FileReader(csvFile));
        reader = new LineNumberReader(new FileReader(csvFile));


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

            cmb1.addItem(location);

            for(int i = 1; i < size; i++){

                if(model.getElementAt(i).equals("from")){
                    cmb1.removeItemAt(i);
                }

                else if(model.getElementAt(i).equals("Bandung")){
                    cmb1.removeItemAt(i);
                }


                for(int j = 2; j < i; j++){
                    if(model.getElementAt(j).equals("Jakarta")){
                        cmb1.removeItemAt(j);
                    }
                }
           }
       }
}

Someone else recommended this approach

boolean isEquals = false;
for(i = 0; i < a && !isEquals; i++){
   isEquals = location.equals("Jakarta");
   if(isEquals){
      cmb1.addItem("Jakarta");
   }
}

This code doesn't work. As the code doesn't stop once it adds a " Jakarta " but it stops after it completed a loop. thus it still creates duplicate within the combobox.

I would like to know if there's any other code i can try. Thank you


回答1:


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


    }


}




回答2:


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.



来源:https://stackoverflow.com/questions/50939372/how-to-add-only-unique-values-from-csv-into-combobox

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