<pre name="code" class="java">//-------------------------------------------------------------------------------------------
// Input & Output
//-------------------------------------------------------------------------------------------
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
double d = reader.nextDouble();
String s = reader.nextLine(); // s = System.console().readLine()
String[] strs = reader.nextLine().split(","); // split supports regex
// Output
System.out.print(n);
System.out.println("double: " + d + ", " + s);
// Output formatting
double pi = Math.PI;
System.out.format("%f%n", pi); // --> "3.141593"
System.out.format("%.3f%n", pi); // --> "3.142"
System.out.format("%10.3f%n", pi); // --> " 3.142"
// Date & Time
Calendar c = Calendar.getInstance();
System.out.format("%tB %te, %tY%n", c, c, c); // --> "May 29, 2016"
System.out.format("%tl:%tM %tp%n", c, c, c); // --> "6:34 pm"
System.out.format("%tD%n", c); // --> "05/29/16"
// 2016-05-08 10:22:52
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Calendar.getInstance().getTime());
Long t1 = System.nanoTime();
final Clock clock = Clock.systemUTC();
System.out.println( clock.instant() ); //2014-04-12T15:19:29.282Z
System.out.println( clock.millis() ); //1397315969360
final LocalDateTime from = LocalDateTime.of( 2014, Month.APRIL, 16, 0, 0, 0 );
final LocalDateTime to = LocalDateTime.of( 2015, Month.APRIL, 16, 23, 59, 59 );
final Duration duration = Duration.between( from, to );
System.out.println( "Duration in days: " + duration.toDays() );
System.out.println( "Duration in hours: " + duration.toHours() );
//-------------------------------------------------------------------------------------------
// Arrays
//-------------------------------------------------------------------------------------------
// native array
int v[] = new int[] {4,3,2,1};
int v[] = new int[3]; // default value is 0
int v[] = {1,2,3};
for(int i = 0; i < v.length; i++) {
System.out.print(v[i] + ", ");
}
// initialize
int[] v = new int[10];
Arrays.setAll(v, idx -> 100); // set all values to 100
Arrays.setAll(v, idx -> v[idx] + 10); // increase each value by 10
Random generator = new Random();
Arrays.setAll(v, idx -> generator.nextInt(1000)); // random value between [0, 1000)
// ArrayList
List<Integer> ar = new ArrayList<>();
ar.add(10);
ar.add(11);
ar.set(1, 20);
for(int i = 0; i < ar.size(); i++)
System.out.print(ar.get(i) + ", ");
List<Integer> ar = new LinkedList<>(); // double linked list
ArrayDeque<Integer> ar = new ArrayDeque<>();
ar.add(10); // == addLast()
ar.addFirst(11);
ar.addLast(20);
// ar.removeFirst(); ar.removeLast();
while(ar.size() > 0) {
System.out.print(ar.poll() + ", ");
}
// PriorityQueue default is min heap
PriorityQueue<Integer> queue = new PriorityQueue<>(10); // min heap with initial capacity 10
//queue = new PriorityQueue<>(10, Collections.reverseOrder()); // max heap
queue.add(10);
queue.peek();
queue.contains(10); // true
queue.poll(); // get & remove top item
// Sort
int ar[] = new int[10];
Arrays.sort(ar); // for native array
// for Collections
List<Integer> ar = new ArrayList<>();
Collections.sort(ar, Collections.reverseOrder())
Collections.sort(ar, (a, b) -> b.compareTo(a));
//-------------------------------------------------------------------------------------------
// String
//-------------------------------------------------------------------------------------------
String s = "abcdefg";
s.charAt(0); // -> a
s.indexOf('b'); // -> 1
s.indexOf("cde"); // -> 2
s.substring(0, 2); // -> "ab"
s.substring(3); // -> "defg"
s.startsWith("abc"); // -> true
s.startsWith("de", 3); // -> true
// String <-> Int conversion:
int a = Integer.parseInt("1234");
String s = 5 + ""; //or String s = Integer.toString(10);
String s = "xyz";
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
}
// Strings are immutable, use StringBuilder to change its content
String s = "abcdefg";
StringBuilder sb = new StringBuilder(s);
sb.setCharAt(0, '1'); // -> "1bcdefg"
sb.insert(2, '2'); // -> "1b2cdefg"
sb.append("123"); // -> "1b2cdefg123"
sb.append(4); // -> "1b2cdefg1234"
sb.append(1.2f); // -> "1b2cdefg12341.2"
sb.delete(2, 3); // -> "1bcdefg12341.2"
sb.deleteCharAt(0); // -> "bcdefg12341.2"
String s2 = sb.toString();
//-------------------------------------------------------------------------------------------
// Loops
//-------------------------------------------------------------------------------------------
int i = 0;
while(i < 10) {
i++;
if(i > 5) break;
if(i == 2) continue;
}
do {
} while(i > 100);
for(int i = 0; i < 10; i++) {
}
int ar[] = new int[10];
for(int a : ar) {
System.out.println(a);
}
int i = 1;
switch(i) {
case 1: System.out.println(i); break;
default: break;
}
//-------------------------------------------------------------------------------------------
// Map and Hash
//-------------------------------------------------------------------------------------------
Map<String, String> map1 = new HashMap<>();
Map<String, String> map2 = Collections.synchronizedMap(new HashMap<String, String>());
Map<String, String> map3 = new ConcurrentHashMap<String, String>();
map1.put("key", "Value");
map1.get("key");
map1.containsKey("key"); // true or false
map1.values(); // all values in type Collection<String>
for(String key : map1.keySet()) {
System.out.println("key = " + key + ", value = " + map1.get(key));
}
// map summary
// HashMap hash table impl
// TreeMap tree impl
// LinkedHashMap keep the insertion order, by adding pointers before & after to ench Entry object
// Collections.synchronizedMap lock at object level
// ConcurrentHashMap lock at finer bucket level
// IdentityHashMap cmp ref(pointer), not key's value
// HashSet hash,impl HashMap
// TreeSet b-tree
// LinkedHashSet keep the insertion order
//-------------------------------------------------------------------------------------------
// Interface and Class
//-------------------------------------------------------------------------------------------
interface Formula {
void normalMethod();
// default implementation support since v1.8
default double sqrt(int a) {
return Math.sqrt(a);
}
}
// class
public final class Galaxy {
// Regular constructor.
public Galaxy(double aMass, String aName) {
fMass = aMass;
fName = aName;
}
// Copy constructor.
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
}
}
//-------------------------------------------------------------------------------------------
// Files
//-------------------------------------------------------------------------------------------
byte[] encoded = Files.readAllBytes(Paths.get(strFilePath));
String s = new String(encoded, StandardCharsets.US_ASCII);
List<String> lines = Files.readAllLines(Paths.get(strFilePath), StandardCharsets.UTF_8);
// Iterate Files in Directory
public static void main(String... args) {
File[] files = new File("C:/").listFiles();
showFiles(files);
}
public static void showFiles(File[] files) {
for (File file : files) {
if (file.isDirectory()) {
System.out.println("Directory: " + file.getName());
showFiles(file.listFiles()); // Calls same method again.
} else {
System.out.println("File: " + file.getName());
}
}
}
try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
//-------------------------------------------------------------------------------------------
// Others
//-------------------------------------------------------------------------------------------
// lamda
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
Collections.sort(names, (String a, String b) -> b.compareTo(a));
Collections.sort(names, (a, b) -> b.compareTo(a));
Arrays.asList( "a", "b", "d" ).forEach( e -> System.out.println( e ) );
Path path = new File( filename ).toPath();
try( Stream< String > lines = Files.lines( path, StandardCharsets.UTF_8 ) ) {
lines.onClose( () -> System.out.println("Done!") ).forEach( System.out::println );
}
// parallel
long[] arrayOfLong = new long[20000];
Arrays.parallelSetAll(arrayOfLong,
index -> ThreadLocalRandom.current().nextInt(1000000));
Arrays.stream(arrayOfLong).limit(10).forEach(
i -> System.out.print(i + " "));
System.out.println();
Arrays.parallelSort(arrayOfLong);
Arrays.stream(arrayOfLong).limit(10).forEach(
i -> System.out.print(i + " "));
System.out.println();
// Base64 support
final String text = "Base64 finally in Java 8!";
final String encoded = Base64
.getEncoder()
.encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded );
final String decoded = new String(
Base64.getDecoder().decode( encoded ),
StandardCharsets.UTF_8 );
System.out.println( decoded );
快速掌握Java语言
最新推荐文章于 2023-01-29 09:00:00 发布