Example usage for java.util List add

List of usage examples for java.util List add

Introduction

In this page you can find the example usage for java.util List add.

Prototype

boolean add(E e);

Source Link

Document

Appends the specified element to the end of this list (optional operation).

Usage

From source file:Main.java

public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<Integer>();

    for (Integer i : Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7))
        numbers.add(i);
    printList(numbers); // 0,1,2,3,4,5,6,7

    // replaces each element with twice its value
    for (int index = 0; index < numbers.size(); index++) {
        numbers.set(index, numbers.get(index) * 2);
    }/*ww w .  ja  va2s .  c  o m*/
    printList(numbers);

    // does nothing because list is not being changed
    for (Integer number : numbers) {
        number++;
    }
    printList(numbers);

    // same as above -- just different syntax
    for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) {
        Integer number = iter.next();
        number++;
    }
    printList(numbers);

    for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) {
        Integer number = iter.next();
        iter.add(number + 1);
    }
    printList(numbers);

    for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext();) {
        Integer number = iter.next();
        if (number % 2 == 0) // if number is even
            iter.remove(); // remove it from the collection
    }
    printList(numbers); // 1,3,5,7,9,11,13,15

    // ListIterator<?> has a "set" method to replace elements
    for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext();) {
        Integer number = iter.next();
        iter.set(number / 2); // divide each element by 2
    }
    printList(numbers); // 0,1,2,3,4,5,6,7

    // Use Java 8 Lambda
    List<Integer> list = numbers;
    list.stream().forEach(elem -> System.out.println("element " + elem));

}

From source file:com.oocl.euc.ita.test.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from ww  w .  j  ava  2  s  .  c  om*/

        //           HttpPost?
        HttpPost httpPost = new HttpPost("http://localhost:8080/qb-webapp/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "Neolarry"));
        nvps.add(new BasicNameValuePair("password", "123456789"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            //                 System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }

        HttpGet httpGet = new HttpGet("http://localhost:8080/qb-webapp/api/trainer");
        System.out.println(httpGet.getURI());
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            //                System.out.println("get: "+response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = "";

            if (entity1 != null) {
                //     
                //                    System.out.println("Response content length: " + entity1.getContentLength());  
                System.out.println(responseString = EntityUtils.toString(entity1));
                // ?                      
            }

            //JsonToObject
            //              JSONArray s = JSONArray.parseArray(responseString);
            //              for (int i = 0; i < s.size(); i++) {
            //                 System.out.println(s.get(i));
            //              }

            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:com.sm.store.TestGZStoreServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-path", "-port", "-mode", "-delay" };
    String[] defaults = new String[] { "store", "./data", "7100", "0", "false" };
    String[] paras = getOpts(args, opts, defaults);
    String p0 = paras[0];/*from w  w w .  j a  va 2 s.c om*/
    int port = Integer.valueOf(paras[2]);
    String path = paras[1];
    int mode = Integer.valueOf(paras[3]);
    boolean delay = Boolean.valueOf(paras[4]);
    String[] stores = p0.split(",");
    List<TupleThree<String, String, Integer>> storeList = new ArrayList<TupleThree<String, String, Integer>>();
    for (String store : stores) {
        storeList.add(new TupleThree<String, String, Integer>(store, path, mode));

    }
    GZRemoteStoreServer rs = new GZRemoteStoreServer(port, storeList, delay);
    logger.info("hookup jvm shutdown process");
    rs.hookShutdown();
    List list = new ArrayList();
    //add jmx metric
    for (String store : stores) {
        list.add(rs.getRemoteStore(store));
    }
    list.add(rs);
    JmxService jms = new JmxService(list);
}

From source file:org.hcmut.emr.SessionBuilder.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    try (BufferedReader br = new BufferedReader(
            new FileReader("/home/sinhlk/myspace/emr/src/main/resources/patern"))) {
        ObjectMapper jsonMapper = new ObjectMapper();
        String line = br.readLine();
        Map<String, String> result = new HashMap<String, String>();
        List<NameValuePair> list = new ArrayList<>();

        while (line != null) {
            if (line != null && line != "") {
                list.add(new BasicNameValuePair(line.trim().toLowerCase(), SessionBuilder.buildValue(line)));
                result.put(line.trim().toLowerCase(), SessionBuilder.buildValue(line));
                line = br.readLine();//  w  w  w.  j  a  va 2  s  .c  o m
            }
        }
        System.out.println(jsonMapper.writeValueAsString(list));
        File file = new File("/home/sinhlk/myspace/emr/src/main/resources/session.js");
        jsonMapper.writeValue(file, list);
    }

}

From source file:com.sm.store.TestStoreServer.java

public static void main(String[] args) {
    String[] opts = new String[] { "-store", "-path", "-port", "-mode", "-delay" };
    String[] defaults = new String[] { "store", "./storepath", "7100", "0", "false" };
    String[] paras = getOpts(args, opts, defaults);
    String p0 = paras[0];//  w  ww  .  j av a2  s. c  o  m
    int port = Integer.valueOf(paras[2]);
    String path = paras[1];
    int mode = Integer.valueOf(paras[3]);
    boolean delay = Boolean.valueOf(paras[4]);
    String[] stores = p0.split(",");
    List<TupleThree<String, String, Integer>> storeList = new ArrayList<TupleThree<String, String, Integer>>();
    for (String store : stores) {
        storeList.add(new TupleThree<String, String, Integer>(store, path, mode));

    }
    RemoteStoreServer rs = new RemoteStoreServer(port, storeList, delay);
    logger.info("hookup jvm shutdown process");
    rs.hookShutdown();
    List list = new ArrayList();
    //add jmx metric
    for (String store : stores) {
        list.add(rs.getRemoteStore(store));
    }
    list.add(rs);
    JmxService jms = new JmxService(list);
}

From source file:com.amazonaws.services.kinesis.samples.datavis.HttpReferrerStreamWriter.java

/**
 * Start a number of threads and send randomly generated {@link HttpReferrerPair}s to a Kinesis Stream until the
 * program is terminated./* www.jav a 2 s .  c  o  m*/
 *
 * @param args Expecting 3 arguments: A numeric value indicating the number of threads to use to send
 *        data to Kinesis and the name of the stream to send records to, and the AWS region in which these resources
 *        exist or should be created.
 * @throws InterruptedException If this application is interrupted while sending records to Kinesis.
 */
public static void main(String[] args) throws InterruptedException {
    if (args.length != 3) {
        System.err.println("Usage: " + HttpReferrerStreamWriter.class.getSimpleName()
                + " <number of threads> <stream name> <region>");
        System.exit(1);
    }

    int numberOfThreads = Integer.parseInt(args[0]);
    String streamName = args[1];
    Region region = SampleUtils.parseRegion(args[2]);

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration());
    AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig);
    kinesis.setRegion(region);

    // The more resources we declare the higher write IOPS we need on our DynamoDB table.
    // We write a record for each resource every interval.
    // If interval = 500ms, resource count = 7 we need: (1000/500 * 7) = 14 write IOPS minimum.
    List<String> resources = new ArrayList<>();
    resources.add("/index.html");

    // These are the possible referrers to use when generating pairs
    List<String> referrers = new ArrayList<>();
    referrers.add("http://www.amazon.com");
    referrers.add("http://www.google.com");
    referrers.add("http://www.yahoo.com");
    referrers.add("http://www.bing.com");
    referrers.add("http://www.stackoverflow.com");
    referrers.add("http://www.reddit.com");

    HttpReferrerPairFactory pairFactory = new HttpReferrerPairFactory(resources, referrers);

    // Creates a stream to write to with 2 shards if it doesn't exist
    StreamUtils streamUtils = new StreamUtils(kinesis);
    streamUtils.createStreamIfNotExists(streamName, 2);
    LOG.info(String.format("%s stream is ready for use", streamName));

    final HttpReferrerKinesisPutter putter = new HttpReferrerKinesisPutter(pairFactory, kinesis, streamName);

    ExecutorService es = Executors.newCachedThreadPool();

    Runnable pairSender = new Runnable() {
        @Override
        public void run() {
            try {
                putter.sendPairsIndefinitely(DELAY_BETWEEN_RECORDS_IN_MILLIS, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {
                LOG.warn(
                        "Thread encountered an error while sending records. Records will no longer be put by this thread.",
                        ex);
            }
        }
    };

    for (int i = 0; i < numberOfThreads; i++) {
        es.submit(pairSender);
    }

    LOG.info(String.format("Sending pairs with a %dms delay between records with %d thread(s).",
            DELAY_BETWEEN_RECORDS_IN_MILLIS, numberOfThreads));

    es.shutdown();
    es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}

From source file:de.jwi.ftp.FTPUploader.java

public static void main(String[] args) throws Exception {
    URL url = new URL("ftp://ftp:none@localhost/tmp");
    String protocol = url.getProtocol();

    String host = url.getHost();/*from  www .  j a v a2  s. c  o  m*/
    String userInfo = url.getUserInfo();
    String path = url.getPath();
    String file = url.getFile();

    File f = new File("D:/temp/out");
    List l = new ArrayList();
    l.add(f);
    String s = upload(url, l);
    System.out.println(s);
    int x = 5;
}

From source file:com.alertlogic.aws.kinesis.test1.StreamWriter.java

/**
 * Start a number of threads and send randomly generated {@link HttpReferrerPair}s to a Kinesis Stream until the
 * program is terminated.//  www  .ja  v a  2 s  .  c  o  m
 *
 * @param args Expecting 3 arguments: A numeric value indicating the number of threads to use to send
 *        data to Kinesis and the name of the stream to send records to, and the AWS region in which these resources
 *        exist or should be created.
 * @throws InterruptedException If this application is interrupted while sending records to Kinesis.
 */
public static void main(String[] args) throws InterruptedException {
    if (args.length != 3) {
        System.err.println(
                "Usage: " + StreamWriter.class.getSimpleName() + " <number of threads> <stream name> <region>");
        System.exit(1);
    }

    int numberOfThreads = Integer.parseInt(args[0]);
    String streamName = args[1];
    Region region = SampleUtils.parseRegion(args[2]);

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration());
    AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig);
    kinesis.setRegion(region);

    // The more resources we declare the higher write IOPS we need on our DynamoDB table.
    // We write a record for each resource every interval.
    // If interval = 500ms, resource count = 7 we need: (1000/500 * 7) = 14 write IOPS minimum.
    List<String> resources = new ArrayList<>();
    resources.add("/index.html");

    // These are the possible referrers to use when generating pairs
    List<String> referrers = new ArrayList<>();
    referrers.add("http://www.amazon.com");
    referrers.add("http://www.google.com");
    referrers.add("http://www.yahoo.com");
    referrers.add("http://www.bing.com");
    referrers.add("http://www.stackoverflow.com");
    referrers.add("http://www.reddit.com");

    HttpReferrerPairFactory pairFactory = new HttpReferrerPairFactory(resources, referrers);

    // Creates a stream to write to with 2 shards if it doesn't exist
    StreamUtils streamUtils = new StreamUtils(kinesis);
    streamUtils.createStreamIfNotExists(streamName, 2);
    LOG.info(String.format("%s stream is ready for use", streamName));

    final HttpReferrerKinesisPutter putter = new HttpReferrerKinesisPutter(pairFactory, kinesis, streamName);

    ExecutorService es = Executors.newCachedThreadPool();

    Runnable pairSender = new Runnable() {
        @Override
        public void run() {
            try {
                putter.sendPairsIndefinitely(DELAY_BETWEEN_RECORDS_IN_MILLIS, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {
                LOG.warn(
                        "Thread encountered an error while sending records. Records will no longer be put by this thread.",
                        ex);
            }
        }
    };

    for (int i = 0; i < numberOfThreads; i++) {
        es.submit(pairSender);
    }

    LOG.info(String.format("Sending pairs with a %dms delay between records with %d thread(s).",
            DELAY_BETWEEN_RECORDS_IN_MILLIS, numberOfThreads));

    es.shutdown();
    es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}

From source file:com.google.demo.translate.Translator.java

public static void main(String[] args) {
    parseInputs();/*www  .j  a  va  2 s .c  om*/

    try {
        String headers = String.join(",", source,
                targets.stream().map(i -> i.toString()).collect(Collectors.joining(",")));

        Files.write(output, Arrays.asList(headers), UTF_8, APPEND, CREATE);

        List<String> texts = new ArrayList<>();
        while (it.hasNext()) {
            texts.add(preTranslationParser(it.next()));
            if (texts.size() == 10 || !it.hasNext()) {
                translate(texts);
                texts = new ArrayList<>();
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        LineIterator.closeQuietly(it);
    }
}

From source file:AverageCost.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    //Directory of the n files
    String directory_path = "/home/gauss/rgrunitzki/Dropbox/Profissional/UFRGS/Doutorado/Artigo TRI15/SF Experiments/IQ-Learning/";
    BufferedReader reader = null;
    //Line to analyse
    String line = "";
    String csvDivisor = ";";
    int totalLines = 1002;
    int totalRows = 532;

    String filesToRead[] = new File(directory_path).list();
    Arrays.sort(filesToRead);//from  w w  w.  j av  a  2s. com
    System.out.println(filesToRead.length);

    List<List<DescriptiveStatistics>> summary = new ArrayList<>();

    for (int i = 0; i <= totalLines; i++) {
        summary.add(new ArrayList<DescriptiveStatistics>());
        for (int j = 0; j <= totalRows; j++) {
            summary.get(i).add(new DescriptiveStatistics());
        }
    }

    //reads all files
    for (String file : filesToRead) {
        reader = new BufferedReader(new FileReader(directory_path + file));
        int lineCounter = 0;
        //reads all file's line
        while ((line = reader.readLine()) != null) {
            if (lineCounter > 0) {
                String[] rows = line.trim().split(csvDivisor);
                //reads all line's row
                for (int r = 0; r < rows.length; r++) {
                    summary.get(lineCounter).get(r).addValue(Double.parseDouble(rows[r]));
                }
            }
            lineCounter++;
        }

        //System.out.println(file.split("/")[file.split("/").length - 1] + csvDivisor + arithmeticMean(avgCost) + csvDivisor + standardDeviation(avgCost));
    }

    //generate mean and standard deviation;
    for (List<DescriptiveStatistics> summaryLines : summary) {
        System.out.println();
        for (DescriptiveStatistics summaryLineRow : summaryLines) {
            System.out.print(summaryLineRow.getMean() + ";" + summaryLineRow.getStandardDeviation() + ";");
        }
    }
}