Example usage for java.util List get

List of usage examples for java.util List get

Introduction

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

Prototype

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) {
    List<Integer> numbers = new ArrayList<Integer>();

    for (Integer i : Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7))
        numbers.add(i);//from ww  w . j  ava2s .c  om
    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);
    }
    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.wwidesigner.modelling.ImpedanceSpectrumPlot.java

/**
 * @param args//w  w w .j a  v  a  2 s  .  c om
 */
public static void main(String[] args) {
    com.jidesoft.utils.Lm.verifyLicense("Edward Kort", "WWIDesigner", "DfuwPRAUR5KQYgePf:CH0LWIp63V8cs2");
    ImpedanceSpectrumPlot plot = new ImpedanceSpectrumPlot();
    try {
        String inputInstrumentXML = "com/wwidesigner/optimization/example/E4-instrument_actual.xml";
        String inputTuningXML = "com/wwidesigner/optimization/example/E4-tuning_actual.xml";

        PhysicalParameters params = new PhysicalParameters(22.22, TemperatureType.C);
        Instrument instrument = plot.getInstrumentFromXml(inputInstrumentXML);
        InstrumentCalculator calculator = new NAFCalculator(instrument, params);

        Tuning tuning = plot.getTuningFromXml(inputTuningXML);
        // Fingering fingering = tuning.getFingering().get(0);
        Fingering fingering = tuning.getFingering().get(7);

        instrument.convertToMetres();

        double freqRange = 1.1;
        int numberOfFrequencies = 10000;
        double targetFreq = fingering.getNote().getFrequency();
        double freqStart = targetFreq / freqRange;
        double freqEnd = targetFreq * freqRange;
        ImpedanceSpectrum impSpectrum = new ImpedanceSpectrum();

        impSpectrum.calcImpedance(instrument, calculator, freqStart, freqEnd, numberOfFrequencies, fingering,
                params);
        impSpectrum.plotImpedanceSpectrum();

        Complex fluteImpedance = calculator.calcZ(targetFreq, fingering);
        String outStr = "Flute impedance: " + fluteImpedance.getReal() + ", " + fluteImpedance.getImaginary()
                + "at " + targetFreq + " Hz";
        System.out.println(outStr);

        ReflectanceSpectrum reflSpectrum = new ReflectanceSpectrum();
        reflSpectrum.calcReflectance(instrument, calculator, 200., 4000., numberOfFrequencies, fingering,
                params);
        List<Double> magMinima = reflSpectrum.getMagnitudeMinima();
        double predFreq = reflSpectrum.getClosestMinimumFrequency(targetFreq);
        outStr = "Flute impedance magnitude minima for " + fingering.getNote().getName() + " "
                + fingering.toString() + " : " + magMinima.get(0) + " " + magMinima.get(1) + " "
                + magMinima.get(2) + " " + magMinima.get(3) + " at target " + targetFreq + " Hz, and predicted "
                + predFreq + " Hz";
        System.out.println(outStr);
        reflSpectrum.plotReflectanceSpectrum(ReflectanceSpectrum.PLOT_REFL_MAGNITUDE_ONLY);
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Predicate<Student> isPaidEnough = e -> e.gpa > 1;
    Predicate<Student> isExperiencedEnough = e -> e.id < 10;

    List<Student> students = Arrays.asList(new Student(1, 3, "John"), new Student(2, 4, "Jane"),
            new Student(3, 3, "Jack"));

    System.out.println(findStudents(students, isPaidEnough));
    System.out.println(findStudents(students, isExperiencedEnough));
    System.out.println(findStudents(students, isExperiencedEnough.and(isPaidEnough)));

    Student somebody = students.get(0);
    System.out.println(findStudents(students, Predicate.<Student>isEqual(somebody)));
}

From source file:Main.java

public static void main(String[] args) {
    Predicate<Student> isPaidEnough = e -> e.gpa > 1;
    Predicate<Student> isExperiencedEnough = e -> e.id < 10;

    List<Student> students = Arrays.asList(new Student(1, 3, "John"), new Student(2, 4, "Jane"),
            new Student(3, 3, "Jack"));

    System.out.println(findStudents(students, isPaidEnough));
    System.out.println(findStudents(students, isExperiencedEnough));
    System.out.println(findStudents(students, isExperiencedEnough.or(isPaidEnough)));

    Student somebody = students.get(0);
    System.out.println(findStudents(students, Predicate.<Student>isEqual(somebody)));
}

From source file:org.voltdb.example.springjdbc.SpringJDBCTemplateTest.java

public static void main(String[] args) throws Exception {

    GenericApplicationContext ctx = new GenericXmlApplicationContext("/applicationContext.xml");
    BeanFactory factory = ctx;/*w ww .  j a  va 2  s. c  o  m*/
    ContestantDao contestantDao = (ContestantDao) factory.getBean("contestantDao");

    List<ContestantData> list = contestantDao.findContestant("0");
    if (list == null || list.size() == 0) {
        contestantDao.insertContestant("foo", "bar", "0");
    }
    list = contestantDao.findContestant("0");
    if (list.size() == 1) {
        System.out.println("Insert Success");
        ContestantData d = list.get(0);
        if (!d.getCode().equals("0") || !d.getFirstName().equals("foo") || !d.getLastName().equals("bar")) {
            System.out.println("Insert failed");
        }
    }
    contestantDao.updateContestant("foo2", "bar2", "0");
    list = contestantDao.findContestant("0");
    if (list.size() == 1) {
        System.out.println("Update Success");
        ContestantData d = list.get(0);
        if (!d.getCode().equals("0") || !d.getFirstName().equals("foo2") || !d.getLastName().equals("bar2")) {
            System.out.println("Update faild");
        }
    }

    contestantDao.insertContestant(null, null, "1");
    list = contestantDao.getAllContestants();
    if (list.size() == 2) {
        System.out.println("Get All Successful.");
    }

    contestantDao.deleteContestant("1");
    System.out.println("Delete was Successful.");
    contestantDao.insertContestant(null, null, "1");
    contestantDao.deleteAllContestants();
    System.out.println("Delete All was Successful.");
}

From source file:com.rmzone.core.App.java

public static void main(String[] args) {
    // set up mongo
    ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringMongoConfig.class);
    MongoOperations mongoOperation = (MongoOperations) ctx.getBean("mongoTemplate");

    // create and save some users
    List<User> users = new ArrayList<User>();
    users.add(new User("1001", "foo", "bar"));
    users.add(new User("1002", "mickey", "mouse"));

    for (User user : users)
        mongoOperation.save("users", user);

    // create and save some documents
    Tire tire = new Tire("Michelin", "Alpine", 1, users.get(0), Calendar.getInstance().getTime(), 14, 12, 3);
    mongoOperation.save("documents", tire);

    Engine engine = new Engine("Model T", "Wow", 1, users.get(0), Calendar.getInstance().getTime());
    engine.setHorsePower(16.4f);/*from   w w w .  j a  v a 2  s.  c o m*/
    mongoOperation.save("documents", engine);

    Car car = new Car("Pinto", "don't touch me!", 1, users.get(0), Calendar.getInstance().getTime());
    car.setMake("Ford");
    car.setColor("Blue");
    car.setEngine(engine);

    // sorry not very elegant
    car.setTires(new ArrayList<Tire>());
    for (int i = 0; i < 4; i++)
        car.getTires().add(tire);
    mongoOperation.save("documents", car);

    // dump all the data        
    List<User> listUser = mongoOperation.getCollection("users", User.class);
    System.out.println("Number of users = " + listUser.size());
    for (User user : listUser)
        System.out.println(user.toString());

    List<DocumentMaster> listDocument = mongoOperation.getCollection("documents", DocumentMaster.class);
    System.out.println("Number of documents = " + listDocument.size());
    for (DocumentMaster document1 : listDocument)
        System.out.println(document1.toString());

    // delete everything
    mongoOperation.dropCollection("users");
    mongoOperation.dropCollection("documents");
}

From source file:amgen.ri.test.TestComparatorChain.java

public static void main(String[] args) throws Exception {
    TestComparatorChain test = new TestComparatorChain();
    List<PseudoRow> in = test.getComparableObjectsOrdered();
    for (PseudoRow row : in) {
        System.out.println(row);//from  ww  w. j a v  a  2  s  .c  o m
    }
    System.out.println();
    int[] sortIndexes = test.go(in);
    for (int sortIndex : sortIndexes) {
        System.out.println(in.get(sortIndex));
    }
}

From source file:com.da.img.ClientFormLogin.java

public static void main(String[] args) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    try {/*w  ww.  j  a v  a 2s  . c  om*/
        HttpGet httpget = new HttpGet("http://www.soraven.info/index.php");

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();
        //System.out.println( EntityUtils.toString(entity));
        System.out.println("Login form get: " + response.getStatusLine());
        EntityUtils.consume(entity);

        System.out.println("Initial set of cookies:");
        List<Cookie> cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-1 " + cookies.get(i).toString());
            }
        }

        HttpPost httpost = new HttpPost("http://www.soraven.info/common/include/login.php");
        Header header1 = new BasicHeader("Accept",
                "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,application/msword, */*");
        Header header2 = new BasicHeader("Referer", "http://www.soraven.info/index.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("p_userid", "bimohani"));
        nvps.add(new BasicNameValuePair("p_passwd", "cw8904"));
        nvps.add(new BasicNameValuePair("x", "12"));
        nvps.add(new BasicNameValuePair("y", "20"));
        httpost.setHeader(header1);
        httpost.setHeader(header2);
        httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        //Thread.sleep(2000);
        response = httpclient.execute(httpost);
        entity = response.getEntity();

        System.out.println("Login form get: " + response.getStatusLine());

        System.out.println(EntityUtils.toString(entity));
        EntityUtils.consume(entity);

        System.out.println("Post logon cookies:");
        cookies = httpclient.getCookieStore().getCookies();
        if (cookies.isEmpty()) {
            System.out.println("None");
        } else {
            for (int i = 0; i < cookies.size(); i++) {
                System.out.println("-2 " + cookies.get(i).toString());
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:edu.illinois.cs.cogcomp.wikifier.utils.freebase.FreebaseSearch.java

public static void main(String[] args) throws Exception {
    FreebaseSearch fb = new FreebaseSearch();
    List<FreebaseAnswer> answers = fb.lookup("Barack_Obama");
    String mid = answers.get(0).getMid().substring(1);
    //      Arrays.asList(answers).forEach(x -> System.out.println(x));

    // for(FreebaseAnswer term:fb.lookup("Obama"))
    // {/*  w w  w . j a  v  a  2s  .co m*/
    // System.out.println(term.getName()+" ");
    // }
    // Map<String, String> map = MapDB
    // .newDefaultDb("data/freebaseRawResponseCache/",
    // "freebase_cache").make().getHashMap("freebase_cache");
    // System.out.println(map.size());
    // int i = 0;
    // for (String key : map.keySet()) {
    // // System.out.println(map.get(key));
    // fb.lookup(key);
    // if (i++ % 1000 == 0) {
    // System.out.println("Done " + i);
    // }
    // }
    // query = "Obomber"; //
    // query = "Saint Ronnie"; // NO!
    // query = "Kstewart"; // NO!
    // query = "Shrub"; /////
    // query = "Mufc"; ///

    // query = "Hogtown"; /////
    // query = "Arnie"; //
    // query = "Owe Bama"; // NO!
    // query = "Belgie"; //

    // query = "MAN U"; //
    // query = "Brittania";

    // query = "heels"; //
    // query = "dprk"; //
    // query = "CFF"; // NO!
    // query = "Hayluh Bawbuh"; // NO!
    // query = "T Dot"; //
    // query = "Chitown"; // NO!
    // query = "Rpattz"; ///
    // query = "Hiltery"; // NO!
    // query = "Baby Bush"; ///
    // query = "Mclame"; // NO!
    // query = "Rob Pattinson";
    // query = "Cigar City"; //
    // query = "Nobama";
    // String[] querys = { "Obomber", "MAN U", "Arnie", "heels", "dprk",
    // "CFF", "Hayluh Bawbuh", "Rob Pattinson", "Cigar City",
    // "Baby Bush", "Hogtown" }; // 11 queries

    // FreebaseSearch search = new FreebaseSearch(
    // "/shared/bronte/tac2014/data/freebaseCache");
    // FreebaseSearch search = new FreebaseSearch();
    // System.out.println(search.lookup("Popolo Delle Liberta'"));
    // FreebaseSearch search = new FreebaseSearch("freebase_cache");
    // System.out.println(search.cache.size());
    // populate(search);
    // System.out.println(search.cache.size());

    // for(String key:search.cache.keySet())
    // {
    // System.out.println(key+" : "+search.cache.get(key));
    // System.out.println(search.cache.get(key).size());
    //
    // // System.out.println(remove_duplicates(search.cache.get(key)));
    // // search.cache.put(key, remove_duplicates(search.cache.get(key)));
    // //
    // System.out.println(remove_duplicates(search.cache.get(key)).size());
    // }
    // int c=0;
    // while(true)
    // {
    // try {
    // search.lookup(query);
    // } catch (Exception e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // c++;
    // System.out.println(c);
    // }
    // for (String query : querys)
    // for (String ans : search.lookup(query)) {
    // System.out.println(ans);
    // }
}

From source file:AmazonKinesisList.java

public static void main(String[] args) throws Exception {
    init();// w  w w.j a v  a 2s.  c om

    final String myStreamName = "anotestBstream";
    final Integer myStreamSize = 1;

    // Create a stream. The number of shards determines the provisioned throughput.

    //        CreateStreamRequest createStreamRequest = new CreateStreamRequest();
    //        createStreamRequest.setStreamName(myStreamName);
    //        createStreamRequest.setShardCount(myStreamSize);

    // pt
    //       kinesisClient.createStream(createStreamRequest);

    // The stream is now being created.
    //       LOG.info("Creating Stream : " + myStreamName);
    //       waitForStreamToBecomeAvailable(myStreamName);

    // list all of my streams
    ListStreamsRequest listStreamsRequest = new ListStreamsRequest();
    listStreamsRequest.setLimit(10);
    ListStreamsResult listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
    List<String> streamNames = listStreamsResult.getStreamNames();
    while (listStreamsResult.isHasMoreStreams()) {
        if (streamNames.size() > 0) {
            listStreamsRequest.setExclusiveStartStreamName(streamNames.get(streamNames.size() - 1));
        }

        listStreamsResult = kinesisClient.listStreams(listStreamsRequest);
        streamNames.addAll(listStreamsResult.getStreamNames());

    }
    LOG.info("Printing my list of streams : ");

    // print all of my streams.
    if (!streamNames.isEmpty()) {
        System.out.println("List of my streams: ");
    }
    for (int i = 0; i < streamNames.size(); i++) {
        System.out.println(streamNames.get(i));
    }

    /*      
          LOG.info("Putting records in stream : " + myStreamName);
          // Write 10 records to the stream
          for (int j = 0; j < 10; j++) {
    PutRecordRequest putRecordRequest = new PutRecordRequest();
    putRecordRequest.setStreamName(myStreamName);
    putRecordRequest.setData(ByteBuffer.wrap(String.format("testData-%d", j).getBytes()));
    putRecordRequest.setPartitionKey(String.format("partitionKey-%d", j));
    PutRecordResult putRecordResult = kinesisClient.putRecord(putRecordRequest);
    System.out.println("Successfully putrecord, partition key : " + putRecordRequest.getPartitionKey()
            + ", ShardID : " + putRecordResult.getShardId());
          }
    */

    // Delete the stream.

    /*      LOG.info("Deleting stream : " + myStreamName);
          DeleteStreamRequest deleteStreamRequest = new DeleteStreamRequest();
          deleteStreamRequest.setStreamName(myStreamName);
            
          kinesisClient.deleteStream(deleteStreamRequest);
          // The stream is now being deleted.
          LOG.info("Stream is now being deleted : " + myStreamName);
                  
          LOG.info("Streaming completed" + myStreamName);
    */

}