Example usage for java.util ArrayList get

List of usage examples for java.util ArrayList get

Introduction

In this page you can find the example usage for java.util ArrayList get.

Prototype

public E get(int index) 

Source Link

Document

Returns the element at the specified position in this list.

Usage

From source file:Main.java

public static void main(String[] args) {
    ResourceBundle bundle = ResourceBundle.getBundle("hello", Locale.US);
    Enumeration<String> keys = bundle.getKeys();
    ArrayList<String> temp = new ArrayList<String>();

    for (Enumeration<String> e = keys; keys.hasMoreElements();) {
        String key = e.nextElement();
        if (key.startsWith("java2s")) {
            temp.add(key);/* ww  w  .  j  a  v  a2s  .  com*/
        }
    }

    String[] result = new String[temp.size()];

    for (int i = 0; i < temp.size(); i++) {
        result[i] = bundle.getString(temp.get(i));
    }
    System.out.println(Arrays.toString(result));
}

From source file:Main.java

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    list.add("E");
    list.add("F");
    list.add("G");
    list.add("H");

    System.out.println(list);//from w w w .j a v  a  2s .co m

    while (!list.isEmpty()) {
        long index = Math.round(Math.floor(Math.random() * list.size()));
        System.out.println("Name " + list.get((int) index));
        list.remove((int) index);
    }

}

From source file:ArrayListDemo.java

public static void main(String[] argv) {
    ArrayList al = new ArrayList();

    // Create a source of Objects
    StructureDemo source = new StructureDemo(15);

    // Add lots of elements to the ArrayList...
    al.add(source.getDate());//from  www .java 2  s  . co m
    al.add(source.getDate());
    al.add(source.getDate());

    // First print them out using a for loop.
    System.out.println("Retrieving by index:");
    for (int i = 0; i < al.size(); i++) {
        System.out.println("Element " + i + " = " + al.get(i));
    }
}

From source file:MainClass.java

public static void main(String[] args) {
    ArrayList myList = new ArrayList(5);
    for (int i = 0; i < 5; i++) {
        myList.add(new Integer(i));
    }/*  w  w  w . jav  a2s.c  o  m*/
    System.out.println("List contains " + myList.size() + " elements");

    Integer int2 = new Integer(2);
    System.out.println("List contains Integer(2): " + myList.contains(int2));
    System.out.println("Integer(2) is at index " + myList.indexOf(int2));

    myList.set(2, new Integer(99));
    System.out.println("Get element at index 2: " + myList.get(2));

    myList.ensureCapacity(15);
    for (int i = 10; i < 15; i++) {
        myList.add(new Integer(i));
    }

    myList.subList(10, 15).clear();
    myList.trimToSize();

    System.out.println(myList);
}

From source file:au.org.ala.layers.grid.GridCacheBuilder.java

public static void main(String[] args) throws IOException {
    logger.info("args[0]=diva grid input dir\nargs[1]=cached diva grid output dir\n\n");

    //load up all diva grids in a directory
    ArrayList<Grid> grids = loadGridHeaders(args[0]);

    //identify groups
    ArrayList<ArrayList<Grid>> groups = identifyGroups(grids);

    //write large enough groups
    for (int i = 0; i < groups.size(); i++) {
        writeGroup(args[1], groups.get(i));
    }//from w ww . j a va2  s  .  co  m
}

From source file:fitmon.Client.java

public static void main(String[] args) throws IOException, ClientProtocolException, NoSuchAlgorithmException,
        InvalidKeyException, SAXException, ParserConfigurationException {
    Food food = null;/* w ww.j  av a  2  s.c om*/
    DietAPI dApi = new DietAPI();
    JDBCConnection jdbcCon = new JDBCConnection();
    ArrayList<Food> foodItems = dApi.getFood();
    Scanner scan = new Scanner(System.in);
    Calendar currentDate = Calendar.getInstance(); //Get the current date
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); //format it as per your requirement
    String dateNow = formatter.format(currentDate.getTime());
    System.out.println("Now the date is :=>  " + dateNow);
    for (int i = 0; i < foodItems.size(); i++) {
        food = foodItems.get(i);
        System.out.println("ID : " + food.getFoodID());
        System.out.println("servingID : " + food.getServingID());
        System.out.println("Name : " + food.getItemName());
        System.out.println("category : " + food.getCategory());
        System.out.println("Quantity : " + food.getQuantity());
        System.out.println("calories : " + food.getCalories());
        System.out.println("fat : " + food.getFat());
        System.out.println("carbs : " + food.getCarbs());
        System.out.println("protein : " + food.getProtein());
        System.out.println("fiber : " + food.getFiber());
        System.out.println("sodium : " + food.getSodium());
        System.out.println("sugar : " + food.getSugar());
        System.out.println("cholesterol : " + food.getCholesterol());
        System.out.println(
                "------------------------------------------------------------------------------------------------");

    }

    System.out.println("Choose a meal......");
    String mealType = scan.next();
    System.out.println("Choose an item......");
    String servingID = scan.next();
    for (int j = 0; j < foodItems.size(); j++) {
        if (foodItems.get(j).getServingID() == null ? servingID == null
                : foodItems.get(j).getServingID().equals(servingID)) {
            food = foodItems.get(j);
            break;
        }

    }
    Diet diet = new CustomizedDiet();
    diet.createDiet(food, mealType, dateNow);

}

From source file:edu.ucla.cs.scai.swim.qa.ontology.dbpedia.tipicality.Test.java

public static void main(String[] args) throws IOException, ClassNotFoundException {
    String path = DBpediaOntology.DBPEDIA_CSV_FOLDER;
    if (args != null && args.length > 0) {
        path = args[0];/*from   w w w  .  ja  v a  2  s  . c  o m*/
        if (!path.endsWith("/")) {
            path = path + "/";
        }
    }

    stopAttributes.add("http://www.w3.org/1999/02/22-rdf-syntax-ns#type");
    stopAttributes.add("http://www.w3.org/2002/07/owl#sameAs");
    stopAttributes.add("http://dbpedia.org/ontology/wikiPageRevisionID");
    stopAttributes.add("http://dbpedia.org/ontology/wikiPageID");
    stopAttributes.add("http://purl.org/dc/elements/1.1/description");
    stopAttributes.add("http://dbpedia.org/ontology/thumbnail");
    stopAttributes.add("http://dbpedia.org/ontology/type");

    try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path + "counts.bin"))) {
        categories = (HashSet<String>) ois.readObject();
        attributes = (HashSet<String>) ois.readObject();
        categoryCount = (HashMap<String, Integer>) ois.readObject();
        attributeCount = (HashMap<String, Integer>) ois.readObject();
        categoryAttributeCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject();
        attributeCategoryCount = (HashMap<String, HashMap<String, Integer>>) ois.readObject();
    }

    System.out.println(categories.size() + " categories found");
    System.out.println(attributes.size() + " attributes found");

    n = 0;
    for (Map.Entry<String, Integer> e : categoryCount.entrySet()) {
        n += e.getValue();
    }

    System.out.println(n);

    HashMap<String, ArrayList<Pair>> sortedCategoryAttributes = new HashMap<>();

    for (String category : categories) {
        //System.out.println(category);
        //System.out.println("-----------");
        ArrayList<Pair> attributesRank = new ArrayList<Pair>();
        Integer c = categoryCount.get(category);
        if (c == null || c == 0) {
            continue;
        }
        HashMap<String, Integer> thisCategoryAttributeCount = categoryAttributeCount.get(category);
        for (Map.Entry<String, Integer> e : thisCategoryAttributeCount.entrySet()) {
            attributesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / c));
        }
        Collections.sort(attributesRank);
        for (Pair p : attributesRank) {
            //System.out.println("A:" + p.getS() + "\t" + p.getP());
        }
        //System.out.println("===============================");
        sortedCategoryAttributes.put(category, attributesRank);
    }

    for (String attribute : attributes) {
        //System.out.println(attribute);
        //System.out.println("-----------");
        ArrayList<Pair> categoriesRank = new ArrayList<>();
        Integer a = attributeCount.get(attribute);
        if (a == null || a == 0) {
            continue;
        }
        HashMap<String, Integer> thisAttributeCategoryCount = attributeCategoryCount.get(attribute);
        for (Map.Entry<String, Integer> e : thisAttributeCategoryCount.entrySet()) {
            categoriesRank.add(new Pair(e.getKey(), 1.0 * e.getValue() / a));
        }
        Collections.sort(categoriesRank);
        for (Pair p : categoriesRank) {
            //System.out.println("C:" + p.getS() + "\t" + p.getP());
        }
        //System.out.println("===============================");
    }

    HashMap<Integer, Integer> histogram = new HashMap<>();
    histogram.put(0, 0);
    histogram.put(1, 0);
    histogram.put(2, 0);
    histogram.put(Integer.MAX_VALUE, 0);

    int nTest = 0;

    if (args != null && args.length > 0) {
        path = args[0];
        if (!path.endsWith("/")) {
            path = path + "/";
        }
    }

    for (File f : new File(path).listFiles()) {
        if (f.isFile() && f.getName().endsWith(".csv")) {
            String category = f.getName().replaceFirst("\\.csv", "");
            System.out.println("Category: " + category);
            ArrayList<HashSet<String>> entities = extractEntities(f, 2);
            for (HashSet<String> attributesOfThisEntity : entities) {
                nTest++;
                ArrayList<String> rankedCategories = rankedCategories(attributesOfThisEntity);
                boolean found = false;
                for (int i = 0; i < rankedCategories.size() && !found; i++) {
                    if (rankedCategories.get(i).equals(category)) {
                        Integer count = histogram.get(i);
                        if (count == null) {
                            histogram.put(i, 1);
                        } else {
                            histogram.put(i, count + 1);
                        }
                        found = true;
                    }
                }
                if (!found) {
                    histogram.put(Integer.MAX_VALUE, histogram.get(Integer.MAX_VALUE) + 1);
                }
            }
            System.out.println("Tested entities: " + nTest);
            System.out.println("1: " + histogram.get(0));
            System.out.println("2: " + histogram.get(1));
            System.out.println("3: " + histogram.get(2));
            System.out.println("+3: " + (nTest - histogram.get(2) - histogram.get(1) - histogram.get(0)
                    - histogram.get(Integer.MAX_VALUE)));
            System.out.println("NF: " + histogram.get(Integer.MAX_VALUE));
        }
    }
}

From source file:edu.cmu.lti.oaqa.knn4qa.apps.ExtractDataAndQueryAsSparseVectors.java

public static void main(String[] args) {
    String optKeys[] = { CommonParams.MAX_NUM_QUERY_PARAM, MAX_NUM_DATA_PARAM, CommonParams.MEMINDEX_PARAM,
            IN_QUERIES_PARAM, OUT_QUERIES_PARAM, OUT_DATA_PARAM, TEXT_FIELD_PARAM, TEST_QTY_PARAM, };
    String optDescs[] = { CommonParams.MAX_NUM_QUERY_DESC, MAX_NUM_DATA_DESC, CommonParams.MEMINDEX_DESC,
            IN_QUERIES_DESC, OUT_QUERIES_DESC, OUT_DATA_DESC, TEXT_FIELD_DESC, TEST_QTY_DESC };
    boolean hasArg[] = { true, true, true, true, true, true, true, true };

    ParamHelper prmHlp = null;/*from  ww w.  j a v a  2  s . co m*/

    try {

        prmHlp = new ParamHelper(args, optKeys, optDescs, hasArg);

        CommandLine cmd = prmHlp.getCommandLine();
        Options opt = prmHlp.getOptions();

        int maxNumQuery = Integer.MAX_VALUE;

        String tmpn = cmd.getOptionValue(CommonParams.MAX_NUM_QUERY_PARAM);
        if (tmpn != null) {
            try {
                maxNumQuery = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(CommonParams.MAX_NUM_QUERY_PARAM, opt);
            }
        }

        int maxNumData = Integer.MAX_VALUE;
        tmpn = cmd.getOptionValue(MAX_NUM_DATA_PARAM);
        if (tmpn != null) {
            try {
                maxNumData = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(MAX_NUM_DATA_PARAM, opt);
            }
        }
        String memIndexPref = cmd.getOptionValue(CommonParams.MEMINDEX_PARAM);
        if (null == memIndexPref) {
            UsageSpecify(CommonParams.MEMINDEX_PARAM, opt);
        }
        String textField = cmd.getOptionValue(TEXT_FIELD_PARAM);
        if (null == textField) {
            UsageSpecify(TEXT_FIELD_PARAM, opt);
        }

        textField = textField.toLowerCase();
        int fieldId = -1;
        for (int i = 0; i < FeatureExtractor.mFieldNames.length; ++i)
            if (FeatureExtractor.mFieldNames[i].compareToIgnoreCase(textField) == 0) {
                fieldId = i;
                break;
            }
        if (-1 == fieldId) {
            Usage("Wrong field index, should be one of the following: "
                    + String.join(",", FeatureExtractor.mFieldNames), opt);
        }

        InMemForwardIndex indx = new InMemForwardIndex(
                FeatureExtractor.indexFileName(memIndexPref, FeatureExtractor.mFieldNames[fieldId]));

        BM25SimilarityLucene bm25simil = new BM25SimilarityLucene(FeatureExtractor.BM25_K1,
                FeatureExtractor.BM25_B, indx);

        String inQueryFile = cmd.getOptionValue(IN_QUERIES_PARAM);
        String outQueryFile = cmd.getOptionValue(OUT_QUERIES_PARAM);
        if ((inQueryFile == null) != (outQueryFile == null)) {
            Usage("You should either specify both " + IN_QUERIES_PARAM + " and " + OUT_QUERIES_PARAM
                    + " or none of them", opt);
        }
        String outDataFile = cmd.getOptionValue(OUT_DATA_PARAM);

        tmpn = cmd.getOptionValue(TEST_QTY_PARAM);
        int testQty = 0;
        if (tmpn != null) {
            try {
                testQty = Integer.parseInt(tmpn);
            } catch (NumberFormatException e) {
                UsageSpecify(TEST_QTY_PARAM, opt);
            }
        }

        ArrayList<DocEntry> testDocEntries = new ArrayList<DocEntry>();
        ArrayList<DocEntry> testQueryEntries = new ArrayList<DocEntry>();
        ArrayList<TrulySparseVector> testDocVectors = new ArrayList<TrulySparseVector>();
        ArrayList<TrulySparseVector> testQueryVectors = new ArrayList<TrulySparseVector>();

        if (outDataFile != null) {
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(CompressUtils.createOutputStream(outDataFile)));

            ArrayList<DocEntryExt> docEntries = indx.getDocEntries();

            for (int id = 0; id < Math.min(maxNumData, docEntries.size()); ++id) {
                DocEntry e = docEntries.get(id).mDocEntry;
                TrulySparseVector v = bm25simil.getDocSparseVector(e, false);
                if (id < testQty) {
                    testDocEntries.add(e);
                    testDocVectors.add(v);
                }
                outputVector(out, v);
            }

            out.close();

        }

        Splitter splitOnSpace = Splitter.on(' ').trimResults().omitEmptyStrings();

        if (outQueryFile != null) {
            BufferedReader inpText = new BufferedReader(
                    new InputStreamReader(CompressUtils.createInputStream(inQueryFile)));
            BufferedWriter out = new BufferedWriter(
                    new OutputStreamWriter(CompressUtils.createOutputStream(outQueryFile)));

            String queryText = XmlHelper.readNextXMLIndexEntry(inpText);

            for (int queryQty = 0; queryText != null && queryQty < maxNumQuery; queryText = XmlHelper
                    .readNextXMLIndexEntry(inpText), queryQty++) {
                Map<String, String> queryFields = null;
                // 1. Parse a query

                try {
                    queryFields = XmlHelper.parseXMLIndexEntry(queryText);
                } catch (Exception e) {
                    System.err.println("Parsing error, offending QUERY:\n" + queryText);
                    throw new Exception("Parsing error.");
                }

                String fieldText = queryFields.get(FeatureExtractor.mFieldsSOLR[fieldId]);

                if (fieldText == null) {
                    fieldText = "";
                }

                ArrayList<String> tmpa = new ArrayList<String>();
                for (String s : splitOnSpace.split(fieldText))
                    tmpa.add(s);

                DocEntry e = indx.createDocEntry(tmpa.toArray(new String[tmpa.size()]));

                TrulySparseVector v = bm25simil.getDocSparseVector(e, true);
                if (queryQty < testQty) {
                    testQueryEntries.add(e);
                    testQueryVectors.add(v);
                }
                outputVector(out, v);
            }

            out.close();
        }

        int testedQty = 0, diffQty = 0;
        // Now let's do some testing
        for (int iq = 0; iq < testQueryEntries.size(); ++iq) {
            DocEntry queryEntry = testQueryEntries.get(iq);
            TrulySparseVector queryVector = testQueryVectors.get(iq);
            for (int id = 0; id < testDocEntries.size(); ++id) {
                DocEntry docEntry = testDocEntries.get(id);
                TrulySparseVector docVector = testDocVectors.get(id);
                float val1 = bm25simil.compute(queryEntry, docEntry);
                float val2 = TrulySparseVector.scalarProduct(queryVector, docVector);
                ++testedQty;
                if (Math.abs(val1 - val2) > 1e5) {
                    System.err.println(
                            String.format("Potential mismatch BM25=%f <-> scalar product=%f", val1, val2));
                    ++diffQty;
                }
            }
        }
        if (testedQty > 0)
            System.out.println(String.format("Tested %d Mismatched %d", testedQty, diffQty));

    } catch (ParseException e) {
        Usage("Cannot parse arguments: " + e, prmHlp != null ? prmHlp.getOptions() : null);
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Terminating due to an exception: " + e);
        System.exit(1);
    }
}

From source file:edu.oregonstate.eecs.mcplan.domains.toy.WeinsteinLittman.java

public static void main(final String[] argv) throws NumberFormatException, IOException {
    final RandomGenerator rng = new MersenneTwister(42);
    final int nirrelevant = 2;

    while (true) {
        final Parameters params = new Parameters(nirrelevant);
        final Actions actions = new Actions(params);
        final FsssModel model = new FsssModel(rng, params);

        State s = model.initialState();
        while (!s.isTerminal()) {
            System.out.println(s);
            System.out.println("R(s): " + model.reward(s));
            actions.setState(s, 0);/*from   w  w w  .  java2  s  .  c o m*/
            final ArrayList<Action> action_list = Fn.takeAll(actions);
            for (int i = 0; i < action_list.size(); ++i) {
                System.out.println(i + ": " + action_list.get(i));
            }
            System.out.print(">>> ");
            final BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
            final int choice = Integer.parseInt(cin.readLine());
            final Action a = action_list.get(choice);
            System.out.println("R(s, a): " + model.reward(s, a));
            s = model.sampleTransition(s, a);
        }
        System.out.println("Terminal: " + s);
        System.out.println("R(s): " + model.reward(s));
        System.out.println("********************");
    }
}

From source file:org.red5.client.net.remoting.DSRemotingClient.java

@SuppressWarnings("rawtypes")
public static void main(String[] args) {
    //blazeds my-polling-amf http://localhost:8400/meta/messagebroker/amfpolling
    DSRemotingClient client = new DSRemotingClient("http://localhost:8400/meta/messagebroker/amfpolling");
    try {/*from www .  j a va  2  s.  co m*/
        client.afterPropertiesSet();
        //send ping
        CommandMessage msg = new CommandMessage();
        msg.setCorrelationId("");
        msg.setDestination("");
        //create / set headers
        ObjectMap<String, Object> headerMap = new ObjectMap<String, Object>();
        headerMap.put(Message.FLEX_CLIENT_ID_HEADER, "nil");
        headerMap.put(Message.MESSAGING_VERSION, 1);
        msg.setHeaders(headerMap);
        msg.setOperation(Constants.CLIENT_PING_OPERATION);
        msg.setBody(new Object[] {});

        Object response = client.invokeMethod("null", new Object[] { msg });
        log.debug("Response: {}\n{}", response.getClass().getName(), response);
        if (response instanceof AcknowledgeMessage || response instanceof AcknowledgeMessageExt) {
            log.info("Got first ACK");
            AcknowledgeMessage ack = (AcknowledgeMessage) response;
            Object id = ack.getHeader(Message.FLEX_CLIENT_ID_HEADER);
            if (id != null) {
                log.info("Got DSId: {}", id);
                client.setDataSourceId((String) id);
            }
        }
        //wait a second for a dsid
        do {
            Thread.sleep(1000);
            log.info("Done with sleeping");
        } while (client.getDataSourceId().equals("nil"));
        //send subscribe
        msg = new CommandMessage();
        msg.setCorrelationId("");
        msg.setDestination("Red5Chat");
        headerMap = new ObjectMap<String, Object>();
        headerMap.put(Message.FLEX_CLIENT_ID_HEADER, client.getDataSourceId());
        headerMap.put(Message.ENDPOINT_HEADER, "my-polling-amf");
        msg.setHeaders(headerMap);
        msg.setOperation(Constants.SUBSCRIBE_OPERATION);
        msg.setBody(new Object[] {});

        response = client.invokeMethod("null", new Object[] { msg });

        if (response instanceof AcknowledgeMessage || response instanceof AcknowledgeMessageExt) {
            log.info("Got second ACK {}", ((AcknowledgeMessage) response));
        }

        //poll every 5 seconds for 60
        int loop = 12;
        do {
            Thread.sleep(5000);
            log.info("Done with sleeping");
            //send poll 
            //0 messages - returns DSK
            //n messages - CommandMessage with internal DSA
            msg = new CommandMessage();
            msg.setCorrelationId("");
            msg.setDestination("Red5Chat");
            headerMap = new ObjectMap<String, Object>();
            headerMap.put(Message.FLEX_CLIENT_ID_HEADER, client.getDataSourceId());
            msg.setHeaders(headerMap);
            msg.setOperation(Constants.POLL_OPERATION);
            msg.setBody(new Object[] {});

            response = client.invokeMethod("null", new Object[] { msg });
            if (response instanceof AcknowledgeMessage) {
                AcknowledgeMessage ack = (AcknowledgeMessage) response;
                log.info("Got ACK response {}", ack);
            } else if (response instanceof CommandMessage) {
                CommandMessage com = (CommandMessage) response;
                log.info("Got COM response {}", com);
                ArrayList list = (ArrayList) com.getBody();
                log.info("Child message body: {}", ((AsyncMessageExt) list.get(0)).getBody());
            }
        } while (--loop > 0);

    } catch (Exception e) {
        log.warn("Exception {}", e);
    }
}