Java9 Immutable Collection

Java9 Immutable Collection
https://dzone.com/articles/immutable-collections-in-java-9
https://docs.oracle.com/javase/9/core/creating-immutable-lists-sets-and-maps.htm#JSCOR-GUID-202D195E-6E18-41F6-90C0-7423B2C9B381

List list3 = List.of("One", "Two", "Three");
Set set3 = Set.of("One", "Two", "Three");
Map map = Map.of("One", "1", "Two", "2", "Three", "3");

Creating Immutable Collection (Java8 or lower)

  • Collections.unmodifiableList(list) 사용
  • Arrays.asList( … ) 사용
  • stream.of(….).collect(collectingAndThen(toList(), Collections::unmodifiableList)) 사용
  • Guava 라이브러리 사용

Difference between Array and ArrayList

  • Resizable
    • Array is static in size that is fixed length data structure, One can not change the length after creating the Array object.
    • ArrayList is dynamic in size. Each ArrayList object has instance variable capacity which indicates the size of the ArrayList. Its capacity grows automatically.
  • Primitives
    • Array can contain both primitive data types (e.g. int, float, double) as well as objects.
    • ArrayList can not contains primitive data types it can only contains objects.
  • Adding elements
    • In array we insert elements using the assignment(=) operator.
    • We can insert elements into the ArrayList using the add() method
  • Length
    • Each array object has the length variable which returns the length of the array.
    • Length of the ArrayList is provided by the size() method.

ArrayArrayList

// Array

int[] integerArray = new int[3];

integerArray[0] = 1;

integerArray[1] = 2;

integerArray[2] = 3;

for (int i : integerArray) System.out.println(i);

for (int j=0; j<integerArray.length; j++) System.out.println(integerArray[ j ]);

int k = 0;

while (k < integerArray.length) System.out.println(integerArray[k++]);

 

// ArrayList

ArrayList<Integer> integerList = new ArrayList<Integer>();

integerList.add(1); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(2); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

integerList.add(3); //cannot store primitive in ArrayList, instead autoboxing will convert int to Integer object

for (int m : integerList) System.out.println(m);

for (int n=0; n<integerList.size(); n++) System.out.println(integerList.get(n));

Iterator<Integer> itr = integerList.iterator();

while (itr.hasNext()) System.out.println(itr.next());

Remove objects from collection

pArrayList에서 iterating하면서 remove() 해야할 경우, Iterator를 사용함.

ArrayList list = new ArrayList(Arrays.asList(“a”,”b”,”c”,”d”));
for (int I = 0; i < list.size(); i++) {
list.remove(i); // 원소가 삭제될 때 list 사이즈가 줄면서 다른 원소들의 index도 바뀜
}

for (String s : list) {
list.remove(s); // ConcurrentModificationException 발생
}

Iterator it = list.iterator();
while (it.hasNext()) {
    String s = it.next(); // Iterator의 next()가 remove()보다 먼저 호출되어야 함
    it.remove();
}

WeatherIndex


// 체감온도값 = 13.12 + 0.6215*T - 11.37 * V^0.16 + 0.3965 * V^0.16 * T [ T: 기온(섭씨), V : 풍속(km/h) ]
public static double calculate(double T, double W) {
	double V = fromMStoKMH(W);
	double value = 0.0;
	if (V > 4.8) {
		value = 13.12 + 0.6215*T - 11.37 * Math.pow(V, 0.16) + 0.3965 * Math.pow(V, 0.16) * T;
		if (value > T) {
			value = T;
		}
	}
	else {
		value = T;
	}
	value = Math.round(value);
	return value;
}

// 열지수값 = -42.379 + (2.04901523*F) + (10.14333127*R) - (0.22475541*F*R) - (0.00683770*F*F) - (0.05481717*R*R) + (0.00122874*F*F*R) + (0.00085282*F*R*R) - (0.00000199*F*F*R*R) [F: 화씨온도, R: 상대습도]
public static double calculate(double T, double R) {
	double F = fromCelsiusToFahrenheit(T);
	double value = -42.379 + (2.04901523*F) + (10.14333127*R) - (0.22475541*F*R) - (0.00683770*F*F) - (0.05481717*R*R) + (0.00122874*F*F*R) + (0.00085282*F*R*R) - (0.00000199*F*F*R*R);	
	double adj = 0.0;
	if (R < 13.0 && F >= 80.0 && F <= 112.0) {
		adj = 0.25 * (13.0 - R) * Math.sqrt((17.0 - Math.abs(F - 95.0)) / 17.0);
	}
	if (R > 85.0 && F >= 80.0 && F <= 87) {
		adj = (R - 85.0)/10.0 * (87.0 - F) / 5.0;
		value += adj;
	}
	if (F < 80.0) {
		value = F;
	}
	value = fromFahrenheitToCelsius(value); // (celsius)
	value = Math.round(value * 10) / 10.0; // 소수점 첫째자리 반올림
	return value;
}

// 부패지수값 = (RH - 65)/14 * (1.054^T) [RH: 상대습도 (%), T: 기온 (섭씨)]
public static double calculate(double T, double RH) {
	double value = (RH - 65.0)/14.0 * Math.pow(1.054, T);
	value = Math.round(value * 100) / 100.0; // 소수점 두째자리 반올림

	return value;
}

PersonStreamTest

//PersonStreamTest – text file read using BinaryStream, Reader
public class PersonStreamTest {

	public static void load1(String filename) {
		FileInputStream fis;
		try {
			fis = new FileInputStream(filename);
			System.out.println("load1 file import: " + filename);
	        int c = 0;

	        while ((c = fis.read()) != -1) {     		
				System.out.println((char)c);
			}		
			fis.close();
			System.out.println("load1 successfully");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void load2(String filename) {
		FileReader fr;
		try {
			fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);
			
			System.out.println("load2 file import: " + filename);
			String line = "";
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}
			br.close();
			fr.close();
			System.out.println("load2 successfully");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void load3(String filename) {
		FileReader fr;
		try {
			fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);

			System.out.println("load3 file import: " + filename);
			String delimiter = ",";
			String line = "";
			while ((line = br.readLine()) != null) {
			    try {   		
	                    // use comma as separator
	                    String[] items = line.split(delimiter);
	                    String name = items[0];
	                    int age = Integer.parseInt(items[1]);
	                    double weight = Double.parseDouble(items[2]);
	                    double height = Double.parseDouble(items[3]);
	                    Gender gender = items[4].equals("FEMALE") ? Gender.FEMALE : Gender.MALE;
 	                    // add Person into person array
	                    Person p = new Person(name, age, weight, height, gender);                	
	                    System.out.println(p);
            	        }
            	        catch (NumberFormatException e) {
			    System.out.println("Error(parseInt or parseDouble)!");           		
            	        }
                  }
		  br.close();
		  fr.close();
		  System.out.println("load3 successfully");
            } catch (FileNotFoundException e) {
        	System.out.println("Error! FileNotFoundException");
            } catch (IOException e) {
        	System.out.println("Error! IOException");
            }
	}

	public static void main(String[] args) {
		String filename = "PersonList.csv";
		
		// command line arguments
		if (args.length >= 1) {
			filename = args[0];
			System.out.println("args0=" + filename);
		}
		load1(filename); // using binary stream
		load2(filename); // using text file reader & buffered reader
		load3(filename); // using text file reader & buffered reader & parse	
	}

}