Random value out of a HashMap

Hi, I'm trying to make a translation program (for testing purposes)
I've put the words and their explanation in a HashMap like
key value
Run --- loop(wich is the translation in dutch)
I'm not sure if this is the right collection i need for it.
Another way i know is to create 2 arrays and do it that way...
But now I want to show a random key out of that Map or just loop trough them,how can that be done.
Can a moderator replace my message to the java newbies section :p I didn't saw it until now.
Message was edited by:
stef569
Message was edited by:
stef569
null
Message was edited by:
stef569
Message was edited by:
stef569

I'm in a generous mood
define this interface
import java.util.Map;
public interface RandomMap extends Map {
     Object getRandomValue();
}define this class
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
public class RandomMapImpl implements RandomMap {
     private Map innerMap;
     public RandomMapImpl() {
          innerMap = new HashMap();
     public Object getRandomValue() {
          List list = new ArrayList(innerMap.values());
          if ( list.isEmpty() ) {
               return null;
          int index = new Random(System.currentTimeMillis()).nextInt(list.size() -1);
          return list.get(index);
     public void clear() {
          innerMap.clear();
     public boolean containsKey(Object key) {
          return innerMap.containsKey(key);
     public boolean containsValue(Object value) {
          return innerMap.containsValue(value);
     public Set entrySet() {
          return innerMap.entrySet();
     public Object get(Object key) {
          return innerMap.get(key);
     public boolean isEmpty() {
          return innerMap.isEmpty();
     public Set keySet() {
          return innerMap.keySet();
     public Object put(Object key, Object value) {
          return innerMap.put(key, value);
     public void putAll(Map t) {
          innerMap.putAll(t);
     public Object remove(Object key) {
          return innerMap.remove(key);
     public int size() {
          return innerMap.size();
     public Collection values() {
          return innerMap.values();
}you could make it simpler still by defining the following class instead
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
public class RandomMapImpl extends HashMap implements RandomMap {
     public Object getRandomValue() {
          List list = new ArrayList(values());
          if ( list.isEmpty() ) {
               return null;
          int index = new Random(System.currentTimeMillis()).nextInt(list.size() -1);
          return list.get(index);
}but I'm not a big fan of class inheritance, it could cause you problems later. up to you

Similar Messages

  • Get a random value out of a query result

    I have a query:
    select id
    from class_schedule
    where id not in (
    select distinct(event_id) from trainer_schedule)I want to pick up a random value from this query result and assign it to a varible e.g. randomID.
    please help

    here is the example
    SQL> SELECT empno,ename
      2  FROM (
      3    SELECT empno,ename
      4    FROM EMP
      5    ORDER BY dbms_random.VALUE)
      6  WHERE ROWNUM = 1;
          7876 ADAMS
    SQL> /
          7566 JONES
    SQL> /
          7900 JAMES
    SQL> /
          7844 TURNER
    SQL>

  • Selecting random values from an array based on a condition

    Hi All,
    I have a small glitch here. hope you guys can help me out.
    I have an evenly spaced integer array as X[ ] = {1,2,3, ....150}. and I need to create a new array which selects 5 random values from X [ ] , but with a condition that these random values should have a difference of atleast 25 between them.
    for example res [ ] = {2,60,37,110,130}
    res [ ] = {10,40,109,132,75}
    I have been thinking of looping thru the X [ ], and selecting randomly but things look tricky once I sit down to write an algorithm to do it.
    Can anyone think of an approach to do this, any help will be greatly appreciated ...

    For your interest, here is my attempt.
    import java.util.Random;
    public class TestDemo {
        public static void main(String[] args) throws Exception {
            for (int n = 0; n < 10; n++) {
                System.out.println(toString(getValues(5, 25, 150)));
        private final static Random RAND = new Random();
        public static int[] getValues(int num, int spread, int max) {
            if (num * spread >= max) {
                throw new IllegalArgumentException("Cannot produce " + num + " spread " + spread + " less than or equals to " + max);
            int[] nums = new int[num];
            int max2 = max - (num - 1) * spread - 1;
            // generate random offsets totally less than max2
            for (int j = 0; j < num; j++) {
                int next = RAND.nextInt(max2);
                // favour smaller numbers.
                if (max2 > spread/2)
                    next = RAND.nextInt(next+1);
                nums[j] = next;
                max2 -= next;
            // shuffle the offsets.
            for (int j = num; j > 1; j--) {
                swap(nums, j - 1, RAND.nextInt(j));
            // add the spread of 25 each.
            for (int j = 1; j < num; j++) {
                nums[j] += nums[j-1] + spread;
            return nums;
        private static void swap(int[] arr, int i, int j) {
            int tmp = arr;
    arr[i] = arr[j];
    arr[j] = tmp;
    public static String toString(int[] nums) {
    StringBuffer sb = new StringBuffer(nums.length * 4);
    sb.append("[ ");
    for (int j = 0; j < nums.length; j++) {
    if (j > 0) {
    sb.append(", ");
    sb.append(nums[j]);
    sb.append(" ]");
    return sb.toString();

  • Weighted random value (1-10) e.g.3 will be  50 % of records

    Hello,
    i need to generate random values into my table. For the simplification, lets say that i need to generate values in range from 1 to 10. For this there is a lot of ways.
    e.g. UPDATE test_number SET random_value = round (dbms_random.value (1,10))
    But what I need is something like weighted random values. I need random values to be inserted into column, but I need e.g. 3 to be inserted more times than other values e.g. if i have 100 rows i want to have 3 in 50 random rows
    Do you have any idea how to achieve it?
    Thanks a lot for any help or reply !

    Hi,
    You can do something like this:
    WITH     got_p_num     AS
         SELECT     LEVEL                         AS id
         ,     FLOOR (dbms_random.value (1, 19))     AS p_num
         FROM     dual
         CONNECT BY     LEVEL     <= 10
    SELECT       id
    ,       p_num
    ,       CASE
              WHEN  p_num     < 3     THEN p_num
              WHEN  p_num     < 12     THEN 3
                                     ELSE p_num - 8
           END     AS r_num
    FROM       got_p_num
    ORDER BY  r_num
    ;If you want the number 3 to appear on half of the rows; that means that, out of 18 random numbers, you expect 3 to occur 9 times, and the other numbers to appear once each. The query above generates random integers in the range 1 through 18 inclusive, and calls this number p_num. The CASE statement maps p_num to what you really want, a n integer between 1 and 10, with 3 occurring 9/18 (= 1/2) of the time.
    Instead of using a CASE expression, you might want to create a table, that has one row for every number that can be in the output, and the probability of picking that number. You could then join to that table to convert the raw random number to the id that you want.
    Edited by: Frank Kulash on Oct 6, 2011 3:36 PM

  • Random Value Generation

    FYI, time to give back. I have received a number of excellent
    responses from this forum, so here is one that might help someone
    else.
    I had found and modified the code below to generate a random
    value (letters and numbers) to use as a member ID. With it you can
    set the length of the generated value, as well as the content
    (numbers, capital letters, lower case letters, even special
    symbols). I chose a subset of capital letters along with 0-9 so the
    result contained more numbers.

    I don't get it?! Why not just use something like
    #createUUID()#, which is also apparently meant to be unique
    everytime.
    If you don't like the format of createUUID you can always run
    a couple of functions over it to alter it a bit, like taking out
    some of the dashes, or making it longer etc.
    Maybe I'm missin the point...it's late here!! Me =
    sleepy.

  • Selecting random records out of a table

    Hi,
    I guess this question isn't new, but I didn't found anything about this using the search of this forum.
    How can I get e.g. 5 random records out of a table?
    I have a small table, which stores the special offers of a shop. Let us say, there are 30 records in it. How can I fetch (e.g.) 5 random records of this table?
    I tried to use this statement in a loop:
    SELECT t_item_id FROM tbl_special_offers SAMPLE (1) WHERE ROWNUM = 1
    But this is a very small table, so most of the query returns no data. Additionally I have to check if this number was already selected and ignore it in this case. This isn't a good solution, is it?
    Can somebody help me out with a better solution? Thanks :)

    create or replace package shop_stuff
    is
       function random_number return number;
    end;
    create or replace package body shop_stuff
    is
       function random_number return number
       is
       begin
          return dbms_random.value;
       end;
    begin
       dbms_random.initialize (to_number(to_char(sysdate,'mmddsssss')));
    end;
    create table tbl_special_offers (t_item_id number);
    insert into tbl_special_offers values (1);
    insert into tbl_special_offers values (2);
    insert into tbl_special_offers values (3);
    insert into tbl_special_offers values (4);
    insert into tbl_special_offers values (5);
    insert into tbl_special_offers values (6);
    insert into tbl_special_offers values (7);
    insert into tbl_special_offers values (8);
    insert into tbl_special_offers values (9);
    insert into tbl_special_offers values (10);
    select t_item_id
      from (select t_item_id
              from tbl_special_offers
             order by shop_stuff.random_number)
    where rownum <= 5                       
    SQL> /
    T_ITEM_ID
             6
             7
             5
             4
            10
    SQL> /
    T_ITEM_ID
             1
             5
             3
             9
             6
    SQL> /
    T_ITEM_ID
             6
             5
             3
             2
            10
    SQL> /
    T_ITEM_ID
            10
             2
             8
             4
             1
    SQL>

  • Build array from random values via ethernet

    Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
    I am using an index array.....but all the values are the same!! How can I sort them??
    It functions correctly with a for loop with random numbers build.......but it doesn't work with the data from ethernet.
    Can someone please help me??
    Attachments:
    Data.vi ‏16 KB

    chendel wrote:
    Am trying to save data that comes from ehternet ((random values (modbus protocol)) in an array.
    I am using an index array.....but all the values are the same!!
    You just read the same shared variable 100 times within a few nanoseconds. Apparently, the variable gets modified less often on the other end.
    chendel wrote:
    How can I sort them??
    If all array values are the same, they are already sorted.
    You need to rethink your code. maybe you can make the shared variable an array and write the entire random array on the other end, the read it out once.
    LabVIEW Champion . Do more with less code and in less time .

  • Stuck on a program to print a number of a RANDOM card out of 52 cards

    Bascically im going through a book called java elemenst and there is a lab little excerise based on the program underneath;
    The prorgram picks a random card out of a deck(52 cards) and simply returns the card number.
    The excercise is that with little moderation i change the program to print the cards value (1..13), followed by the number of suit (clubs are 1, spades are 4)
    Ive tried but i make it too hard and too complicated when this for a begginer whilst i make it out as thought im much more!!i tried a if statement after making a variable spade and hearts but i then make casting problems.
    Please can someone help me with such a easy program,and give me the code to make it work,i know the answer is probally in a few lines(cos its teh fisrt few pages of the book for begginers!!)
    thank you anyway and heres the orginal working unchanged code ;
    import java.util.Random;
    public class Card
        public static void main(String args[])
            Random random = new java.util.Random();
            int drawn;
            // and add 1 to get a random integer 1..52
            drawn = java.lang.Math.abs(random.nextInt())%52+1;
              //i
            System.out.println("the card drawn is number " + drawn);
        }

    The Java Tutorials are your friend(s). Use them. The following code is from here : [http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html|http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html]
    import java.util.*;
    public class Card {
        public enum Rank { DEUCE, THREE, FOUR, FIVE, SIX,
            SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
        public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
        private final Rank rank;
        private final Suit suit;
        private Card(Rank rank, Suit suit) {
            this.rank = rank;
            this.suit = suit;
        public Rank rank() { return rank; }
        public Suit suit() { return suit; }
        public String toString() { return rank + " of " + suit; }
        private static final List<Card> protoDeck = new ArrayList<Card>();
        // Initialize prototype deck
        static {
            for (Suit suit : Suit.values())
                for (Rank rank : Rank.values())
                    protoDeck.add(new Card(rank, suit));
        public static ArrayList<Card> newDeck() {
            return new ArrayList<Card>(protoDeck); // Return copy of prototype deck
    }Then once you have the ArrayList of Cards use Collections.shuffle(list) to randomize the deck and then you can deal the cards

  • New OSX not does not work with RED Rocket Card and old OSX Randomly Logs Out - UNSTABLE

    It looks like my MBPR 16GB (MacBook Pro) randomly logs out and causes my programs to quit unsaved.  I can not update to the new OSX mountain Lion because the new Apple release is no longer compatible with the RED Rocket card needed for debaying RED Scarlet footage.  Mountain Lion causes the RED Rocket to not run correctly with Adobe Premiere. 
    At the same time, I am on Lion and my computer randomly logs me out and I lose all my work.  It seems as though the Retina is unstable. 
    Any help would be greatly appreciated.  Can someone tell me how I can return this.  It seems as though I may have to switch the entire company over to PC if this is not figured out soon. 

    You probably have not received responses for two reasons.
    1. There are not many here that know what this is "RED Rocket card needed for debaying RED Scarlet footage"
    2. Your post appears to contain some sort of threat to Apple about moving to PCs. You are not addressing Apple here. We are users just like you. We don't care if you change over to PCs.
    MBPs and Lion are very stable. Maybe your unsupported third party Red card is causing issues. Their answer seems to be that Mountain Lion is not supported. I wonder why?
    My suggestion if this is a business environment is to not mess with this. If you know for a fact that your Red card works with PCs, change over to PCs. I know that if some tool was not working for my business I would not hesitate to get something that worked.

  • How can i get the random values from database?

    Hi,
    i want to get random values from database.
    I try my best find no solution
    plz give solution in either sql query or java method.
    thanks in advance.

    try this:
    Give a numeric row-id to each row of database.
    say (1-100) for 100 rows
    In the program use random function to get random number between 0 and 1. this value u multiply with 100(or total number of rows) and take integer value of it . u then perform sql query to select the a row which matches randomly genarated value with row-id assigned to each row of database
    madhu

  • Error : CLI0111E Numeric value out of range

    Hello:
    While extracting data through generic datasources, extraction fails in the source system with the following error message.
    Database error text........: "CLI0111E Numeric value out of range.
    SQLSTATE=22003 row=1 col=12"
    Any idea what does this mean?
    Thanks

    Hello:
    While extracting data through generic datasources, extraction fails in the source system with the following error message.
    Database error text........: "CLI0111E Numeric value out of range.
    SQLSTATE=22003 row=1 col=12"
    Any idea what does this mean?
    Thanks

  • Bcp import error numeric value out of range

    lo, I have table with columns of type int. I export this table by using bcp:
    bcp dbo.int_table out file.dat -q -CRAW -T -S localhost -E . 
    Now I want to import it to table with columns of type bigint. I use bcp command:
    bcp dbo.bigint_table in file.dat -q -CRAW -T -S localhost -E 
    I get error:
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    i was trying import table by using format file created based on bigint_table by command:
    bcp dbo.bigint_table in file.dat -f format_file_bigint.xml -q -CRAW -T -S localhost -E
    but i also gets the same errors. 
    Can I use format file when during export was used -CRAW option???? 

    int table:
    CREATE TABLE [INT_TABLE](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [COL1] [int] NOT NULL,
        [COL2] [datetime] NOT NULL,
        [COL3] [datetime] NOT NULL,
        [COL4] [datetime] NOT NULL,
        [COL5] [datetime] NOT NULL,
        [COL6] [bit] NOT NULL,
        [COL7] [bit] NOT NULL,
        [COL8] [numeric(15,2)] NOT NULL,
        [COL7] [numeric(15,2)] NOT NULL,
        [COL8] [numeric(15,2)] NOT NULL,
        [COL9] [int] NOT NULL,
        [COL10] [int] NOT NULL,
        [COL11] [datetime] NULL
    big int table:
    CREATE TABLE [BIGINT_TABLE](
        [ID] [int] IDENTITY(1,1) NOT NULL,
        [COL1] [int] NOT NULL,
        [COL2] [datetime] NOT NULL,
        [COL3] [datetime] NOT NULL,
        [COL4] [datetime] NOT NULL,
        [COL5] [datetime] NOT NULL,
        [COL6] [bit] NOT NULL,
        [COL7] [bit] NOT NULL,
        [COL8] [numeric(15,2)] NOT NULL,
        [COL7] [numeric(15,2)] NOT NULL,
        [COL8] [numeric(15,2)] NOT NULL,
        [COL9] [bigint] NOT NULL,
        [COL10] [bigint] NOT NULL,
        [COL11] [datetime] NULL
    The int table was exported by bcp command:
    bcp int_table out 'c:\int_table.dat' -q -N -T -C RAW -S localhost
    and i try import it by command:
    bcp bigint_table in 'c:\int_table.dat' -T -C RAW -q -S localhost -E
    then i get this errors:
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0
    Error = [Microsoft][SQL Native Client]Numeric value out of range
    SQLState = 22003, NativeError = 0

  • JMS Queue XML numeric value out of range

    Hi
    I have an interface that process the root element of the JMS message.
    It is failing on the step Load JMS to XML. The error states: numeric value out of range.
    I've analysed the message and determined the exact data item which is 11 digits long.
    The JMS model only accomodates for numeric(10,0). I tried changing it, but still get the error.
    Any idea what I need to do so that this step will process that data without error?
    Cheers
    PS ODI 11.1.1.6

    Hi All,  I have one scenario to read the source file . The file delimiter is '|' . The no of pipeline for each line is 17. So if a line containing more than 17 , send an error email. For this first i am printing tota pipeline in ecah line to afile called pipelinecount.txt . Then i will read this file and send each value to while loop /for loop , where it will get > 17 , it will exit the process and send an email.  But here in script i am getting error at while line. Could anyone help.   #! /bin/kshset -x SOURCE_DIR=/vp01/SrcFilessed 's/[^|]//g' /vp01/SrcFiles/Test.txt | awk '{ print length }'> /vp01/SrcFiles/pipelinecount.txtcd $SOURCE_DIRwhile line in `cat pipelinecount.txt`; do if [ $line -eq 17 ];thenecho "No issue in pipeline"exit 0;fiif [ $line -gt 17 ];thenecho "No of pipelines exceeded the expected. Please verify the source file." | mailx -s "WKFS Load: Failed" [email protected]

  • CRAXDDRT PrintOutEx method throes 'value out of range' error

    Hi,
    I am using CRAXDDRT.dll for Crystal reports 10 to print a report to a file in afp format.
    The following is the scenario:
    We have to print out the Tax forms of all the accounts. These forms are printed through an AFP printer. We generate the AFP file and push it to the printer for printing. We create the files each containg10000 accounts. So, we create multiple afp files going in a loop in our code, breaking our files to contain 10000 accounts. For writing the report to a file we use the PrintOutEx method of CRAXDDRT.dll which also takes StartPage number and StopPage numbers as parameters. But when either of the parameters exceeds 32000(int) the method fails with a 'value out of range' error. Do we have any hot fix so that the PrintOutEx method accepts StartPageNum and StopPageNum values more than 32000.
    Public crReport As CRAXDDRT.ReportClass
    crReport.PrintOutEx(False, piCopiesToPrinter, True, 33000, 38000, sPortName)
    Thanks.

    CR 10 has been out of patch support since december of 07. See the following for more details:
    Business Objects Product Lifecycles [original link is broken]
    There is no equivalent API to PrintOutEx in the Crystal Reports SDK for .NET. Thus I understand why you need to use the RDC. However, my suggestion of changing your reference to craxDrt.dll as opposed to craxDDrt.dll still stands due to the two reasons I gave in my previous post (licensing and stability).
    I would also consider Don's suggestion re. the 32K limit:
    "Only work around I can think of is to limit the number of pages for your print jobs to 32K and then create multiple print jobs to select the same limit. Using Record Selection formula to set the limit, as for the actual page numbers being printed you will likely have to limit them also to 32k, the field may not be able to hold any page numbers higher than 32k."
    Finally, another suggestion worth investigating is to see if CR XI release 2 with the latest Service Pack has the same issue. CR XI r2 eval can be downloaded from here:
    http://www.businessobjects.com/products/reporting/crystalreports/eval.asp
    The latest Service Pack can be downloaded from here:
    https://smpdl.sap-ag.de/~sapidp/012002523100013876392008E/crxir2win_sp5.exe
    Ludek

  • Why does the iPhone randomly exit out of apps??

    Hello what should I do about my iPhone 4S randomly exiting out of apps? I've held the top and middle buttons at the same time many of times and its not helping! It's still occurring! Help!!!

    An app randomly exiting means that the app has "crashed".  You might have a bad app (try deleting it form your device and re-downloading it).  It might be an app bug which you just happen to be encountering.  It could also be a problem with your iPhone.  You could do a "restore as new" and re-instsall the apps and see if they have the same issues or not.  It they don't, then it was either a bad download, or corruption in your "profile".

Maybe you are looking for