8. Libraries
8.1. Math
1for (int i = 0; i < 5; i++) {
2 var num = Math.random();
3 var s = String.format("%.5f", num);
4 System.out.println(s);
5}
8.2. StringBuilder
1var entity = "One-Off Coder";
2var address = "7526 Old Linton Hall Road";
3var city = "Gainesville";
4var state = "VA";
5var zip = 20155;
6var www = "https://www.oneoffcoder.com";
7var email = "info@oneoffcoder.com";
8
9var label = new StringBuilder()
10 .append(entity).append('\n')
11 .append(address).append('\n')
12 .append(city).append(' ')
13 .append(state).append(' ')
14 .append(zip).append('\n')
15 .append(www).append('\n')
16 .append(email)
17 .toString();
18
19System.out.println(label);
8.3. HTTP
1import java.net.URI;
2import java.net.http.HttpClient;
3import java.net.http.HttpRequest;
4import java.net.http.HttpResponse;
1String uri = "http://www.oneoffcoder.com";
2
3HttpClient client = HttpClient.newHttpClient();
4HttpRequest request = HttpRequest.newBuilder()
5 .uri(URI.create(uri))
6 .build();
7
8HttpResponse<String> response =
9 client.send(request, HttpResponse.BodyHandlers.ofString());
10
11String body = response.body();
12
13System.out.println(body.length());
8.4. CSV
8.4.1. Writing data to a CSV
1import com.opencsv.CSVWriterBuilder;
2import com.opencsv.ICSVParser;
3import com.opencsv.ICSVWriter;
4import java.io.FileWriter;
1var writer = new CSVWriterBuilder(new FileWriter("demo.csv"))
2 .withSeparator(ICSVParser.DEFAULT_SEPARATOR)
3 .withQuoteChar(ICSVParser.DEFAULT_QUOTE_CHARACTER)
4 .withEscapeChar(ICSVParser.DEFAULT_ESCAPE_CHARACTER)
5 .withLineEnd(ICSVWriter.DEFAULT_LINE_END)
6 .build();
7
8var entries = new String[][] {
9 { "first_name", "last_name" },
10 { "John", "Doe" },
11 { "Jane", "Smith" }
12};
13
14for (String[] row : entries) {
15 writer.writeNext(row);
16}
17
18writer.close();
8.4.2. Reading data from a CSV
1import com.opencsv.CSVParserBuilder;
2import com.opencsv.CSVReaderBuilder;
3import com.opencsv.ICSVParser;
4import java.io.FileReader;
1final var parser = new CSVParserBuilder()
2 .withSeparator(ICSVParser.DEFAULT_SEPARATOR)
3 .withQuoteChar(ICSVParser.DEFAULT_QUOTE_CHARACTER)
4 .withEscapeChar(ICSVParser.DEFAULT_ESCAPE_CHARACTER)
5 .build();
6
7final var reader = new CSVReaderBuilder(new FileReader("demo.csv"))
8 .withSkipLines(1)
9 .withCSVParser(parser)
10 .build();
11
12String[] line;
13while ((line = reader.readNext()) != null) {
14 for (int i = 0; i < line.length; i++) {
15 System.out.print(line[i]);
16 if (i < line.length - 1) {
17 System.out.print(", ");
18 } else if (i == line.length - 1) {
19 System.out.println();
20 }
21 }
22}
23
24reader.close();
8.5. Static imports
1import static java.lang.Math.pow;
2import static java.lang.Math.sqrt;
1var num = 100.0d;
2var s = sqrt(num);
3var p = pow(num, 2.0d);
8.6. String tokenization
1import java.util.StringTokenizer;
1String s = "firstName=John; lastName=John; age=18";
2
3StringTokenizer tokenizer = new StringTokenizer(s, "=;");
4
5while (tokenizer.hasMoreTokens()) {
6 String key = tokenizer.nextToken().strip();
7 String val = tokenizer.nextToken().strip();
8
9 System.out.println(key + " is " + val);
10}
8.7. Optional
8.7.1. Basic use of optional
1import java.util.Optional;
1var x = Optional.of("John");
2// check if empty
3System.out.println(x.isEmpty()); // false
4
5// get value
6System.out.println(x.get()); // John
8.7.2. Nullable optional
1import java.util.Optional;
1var x = Optional.ofNullable(null);
2// check if empty and presentOptionalExample
3System.out.println(x.isEmpty()); // true
4System.out.println(x.isPresent()); // false
5
6System.out.println(x.orElse("No name!"));
8.8. Date
8.8.1. Basic date
1import java.util.Date;
1Date date = new Date();
2
3System.out.println(date.getTime());
8.8.2. Basic calendar
1import java.text.SimpleDateFormat;
2import java.util.Calendar;
3import static java.lang.String.valueOf;
4import static java.lang.String.format;
1Calendar calendar = Calendar.getInstance();
2
3var month = calendar.get(Calendar.MONTH) + 1;
4var day = calendar.get(Calendar.DATE);
5var year = calendar.get(Calendar.YEAR);
6var hour = calendar.get(Calendar.HOUR);
7var minute = calendar.get(Calendar.MINUTE);
8var second = calendar.get(Calendar.SECOND);
9
10String date = String.join("-",
11 valueOf(year),
12 format("%02d", month),
13 format("%02d", day));
14
15String time = String.join(":",
16 format("%02d", hour),
17 format("%02d", minute),
18 format("%02d", second));
19
20System.out.println(date + " " + time);
21
22// or use SimpleDateFormat
23SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
24System.out.println(formatter.format(calendar.getTime()));
8.8.3. Calendar creation
1import java.text.SimpleDateFormat;
2import java.util.Calendar;
3import java.util.GregorianCalendar;
1Calendar calendar = new GregorianCalendar(2019, 0, 31);
2
3SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
4System.out.println(formatter.format(calendar.getTime()));
8.8.4. Calendar manipulation
1import java.text.SimpleDateFormat;
2import java.util.Calendar;
1SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
2
3Calendar calendar = Calendar.getInstance();
4
5// add 1 year
6calendar.add(Calendar.YEAR, 1);
7System.out.println(formatter.format(calendar.getTime()));
8
9// subtract 2 years
10calendar.add(Calendar.YEAR,-2);
11System.out.println(formatter.format(calendar.getTime()));
8.9. Random number generation
1import java.util.Random;
1Random random = new Random(37L);
2
3var a = random.nextBoolean();
4var b = random.nextDouble();
5var c = random.nextInt();
6var d = random.nextInt(100);
7var e = random.nextFloat();
8var f = random.nextGaussian();
9var g = random.nextLong();