Showing posts with label ArrayList. Show all posts
Showing posts with label ArrayList. Show all posts

Create ArrayList (ArrayList) from array (T[])

Question:
I have an array that is initialized like:
  Element[] array = {new Element(1), new Element(2), new Element(3)};

I would like to convert this array into an object of the ArrayList class:
  ArrayList arraylist = ???;

Answer:
new ArrayList(Arrays.asList(array))

Code:
import java.util.*;
 
public class ArrayToArrayList {
 
  public static void main(String[] args) {
 
    String[] array = {new String("aaa"),new String("bbb"),new String("ccc")};
 
    ArrayList<String> list = new ArrayList<String>(Arrays.asList(array));
 
    System.out.println("array: " + Arrays.toString(array));
    System.out.println("list: " + list);
 
  }
}

Output:
$ java ArrayToArrayList
array: [aaa, bbb, ccc]
list: [aaa, bbb, ccc]

How to empty an ArrayList in java.

Question:
How to empty an ArrayList?

Answer:

Code:
import java.util.ArrayList;
 
public class EmptyArrayList { 
  public static void main(String[] args) { 
    ArrayList<String> list = new ArrayList<String>();
 
    list.add("John");
    list.add("Ringo");
    list.add("George");
 
    System.out.println("ArrayList: "+ list);
 
    list.add("Paul");
    System.out.println("ArrayList: "+ list);
 
    list.add("Me");
    list.clear();
    System.out.println("ArrayList: "+ list);
  } 
}
 

Output:
$ java EmptyArrayList
ArrayList: [John, Ringo, George]
ArrayList: [John, Ringo, George, Paul]
ArrayList: []

How to populate contents of a file into an ArrayList?

Question:
I have a file that has two columns of integers that need to be read in and populated into two separate ArrayLists with its content.

Code:
import java.io.*;
import java.util.*;
 
public class FileIntoArray {
   public static void main(String[] args) {
 
      ArrayList<Integer> col1 = new ArrayList<>(); 
      ArrayList<Integer> col2 = new ArrayList<>(); 
 
      try {
         FileInputStream is = new FileInputStream("data.txt");
         BufferedReader br = new BufferedReader(new InputStreamReader(is));
 
         String str;
         String values[]; 
 
         while ((str = br.readLine()) != null) {
            values = str.split(" "); 
            col1.add(Integer.parseInt(values[0])); 
            col2.add(Integer.parseInt(values[1])); 
         }
      } catch (Exception e) {
         // needs better exception handling in real world
         System.out.println(e.toString());
         col1.clear();
         col2.clear();
      }
      System.out.println("col1: " + col1);
      System.out.println("col2: " + col2);
   }
}

Output:
$ java FileIntoArray 
col1: [115, 123, 116, 113, 112, 104, 110, 218, 208]
col2: [257, 253, 246, 243, 239, 239, 238, 243, 242]

$ cat data.txt 
115 257
123 253
116 246
113 243
112 239
104 239
110 238
218 243
208 242