Travs
Travs

Reputation: 83

Grabbing random index of dataclass list

Okay so I have this

public static List<DataValue> result = new LinkedList<>();

public static class DataValue {
    protected final String first;
    protected final int second;

    public DataValue(String first, int second) {
        this.first = first;
        this.second = second;
    }
}

adding to list...

    String first = "bob";
    int second = "50";
    result.add(new DataValue(first, second));

I'm trying to grab a random field from the data, display it, then remove it from the list so it doesn't get used again

How would I go about doing this?

My current attempt at even grabbing the data havn't gone very well

System.out.println("First: "+DataValue.result.getFirst());

and also tried System.out.println("First: "+result.getFirst(DataValue));

I'm not sure how to grab it and couldn't find any articles about it, any help is appreciated

There's about 5000 entries in the LinkedList if that makes any difference

Upvotes: 1

Views: 47

Answers (2)

Esteban Filardi
Esteban Filardi

Reputation: 736

I don't understand well your question but you could try something like this

Random randomGenerator;
int randomIndex = randomGenerator.nextInt( result.size() );
DataValue dataValue = result.get( randomIndex );
//... Show the fields ...
result.remove( randomIndex );`

Upvotes: 1

lol
lol

Reputation: 3390

How about this?

import java.util.LinkedList;
import java.util.List;

public class MyClass {
    public static List<DataValue> result = new LinkedList<DataValue>();

    public static class DataValue {
        protected final String first;
        protected final int second;

        public DataValue(String first, int second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public String toString(){
            return first + " " + second;
        }
    }

    public static void removeAndPrintRandom(){
        int index = (int)(Math.random() * result.size());
        System.out.println(result.remove(index));
    }
}

I have just shown you better method to do this. You can edit this and make according to your requirement.

Upvotes: 0

Related Questions