简体   繁体   中英

Lists in Java - Adding values to their keys (HashMap or HashSet or other)

I want to sort my LineChart X axis in JavaFX. I have Dates(X axis) from DatePicker and their Values(Y axis), but there are for exaple four exactly the same dates and different values. What I want to do is that I need to check if date exist, and if yes, I want to add the value to that date. Sorry about my english.

Look at my Linechart.

我的应用程式中的折线图

The first date has three values. I want to add them.

here is my code:

void initLineChart()
{

    //defining a series
    XYChart.Series<String,Number> series = new XYChart.Series<String, Number>();
    lineChart.setAxisSortingPolicy(LineChart.SortingPolicy.X_AXIS);

    String date = new String();
    int numb;
    String value = new String();;



    ShowDreamHistoryController.save();
    ShowDreamHistoryController.loadDreamAtStart();

    for (int i = 0; i < ShowDreamHistoryController.listDreams.size(); i++) {

        date = ShowDreamHistoryController.listDreams.get(i).getDate().toString();


        value = ShowDreamHistoryController.listDreams.get(i).getHours();


        if(value != null)
        {
        numb = Integer.valueOf(value);
        series.getData().add(new XYChart.Data<String,Number>(date, numb));
        }
    }//for

      //  System.out.println(datesOnes);
    lineChart.getData().add(series);
}

Check if the date exists in series and if it does, remove that index and add to it.

        int indexExist = existAt(series,date);

        if(indexExist < 0){   // if the date does not exist
            series.getData().add(new XYChart.Data<String, Number>(date, numb));
        } else { //if the date exists
            int curVal = series.getData().get(indexExist).getYValue().intValue();
            //get the current value stored in that date
            series.getData().remove(indexExist);
            // remove the index
            series.getData().add(indexExist, new XYChart.Data<String,Number>(date, curVal + value));
            // add to that index ( current value + value )
        }

Then we would have a function that looks for the index.

/*
    Loop through "SERIES" and return the position of the string
    -1 if it doesn't exist.
*/
public int existAt(XYChart.Series <String, Number> series, String date){
    for(int i=0; i<series.getData().size(); i++){
        if(series.getData().get(i).getXValue().equals(date)){
            return i;
        }
    }
    return -1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM