0
My Csv Structure is like this : -
apple,juicy
apple,red,
apple,fruit
ball,round
ball,baseball
ball,soccer
ball,field hockey

如何获取与第一列中相同元素相对应的随机元素 - 例如,对于苹果,它随机选择多汁,对于球,它随机选择足球,或者当程序下次再次运行时,它给出苹果作为水果和球。我对如何做到这一点一无所知,

到目前为止,我的代码是这样的 -

 ArrayList<String> column1 = new ArrayList<String>();

        String key=keyword[0];
        for(int i=1;i<keyword.length;i++){

            if(keyword[i].equals(keyword[i-1])){
                AlternateNew.add(alternate[i-1]);
            }else{
                column1.add(keyword[i-1];
            }

            }

如何为第二列获取类似的数组集,其中第二个数组包含 csv 第二列的随机生成的元素?

我的输出应该有两个不同的数组,它们是 - array1={apple,ball} :对于第一列数组 array2={juicy,soccer} :对于第二列,其中 juicy 和 football 是从对应于苹果元素的元素中随机选择的分别在第一列和足球。

下次程序运行时输出是 - array1={apple,ball} array2={red,field hockey}

4

2 回答 2

0

In order to pick one of the set of values that has the same first value from the file, use a map structure with a list for the values. Like this:

TreeMap<String, ArrayList<String>>

When reading, add entries into the map, making sure to initialize the list for new keys, and add to the existing list for existing keys. The first value from the file is the key. The second is a value to insert into the ArrayList.

Once the map is filled, iterate over the map keys (using a TreeMap, they will be in alphabetical order). On each iteration, find the size of the list, generate a random number between 0 and (size - 1), then pull out that element of the ArrayList.

I hesitate to write code for this answer because this sounds a lot like a homework problem.

于 2013-09-07T07:20:18.777 回答
0

You can use collection interface to put the elements in a set and then you can use mapping using map collection framework

于 2013-09-07T07:21:27.300 回答