Map<Integer, Integer> squares = new HashMap<Integer, Integer>();
java
public void printList(List<?> list, PrintStream out) throws IOException {
for (Iterator<?> i = list.iterator(); i.hasNext(); ) {
out.println(i.next().toString());
}
}
linux
public static <A extends Number> double sum(Box<A> box1,Box<A> box2){
double total = 0;
for (Iterator<A> i = box1.contents.iterator(); i.hasNext(); ) {
total = total + i.next().doubleValue();
}
for (Iterator<A> i = box2.contents.iterator(); i.hasNext(); ) {
total = total + i.next().doubleValue();
}
return total;
}
web
public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap<AntStatus, String> antMessages =
new EnumMap<AntStatus, String>(AntStatus.class);
// Initialize the map
antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
antMessages.put(AntStatus.COMPILING, "Compiling Java classes...");
antMessages.put(AntStatus.COPYING, "Copying files...");
antMessages.put(AntStatus.JARRING, "JARring up files...");
antMessages.put(AntStatus.ZIPPING, "ZIPping up files...");
antMessages.put(AntStatus.DONE, "Build complete.");
antMessages.put(AntStatus.ERROR, "Error occurred.");
// Iterate and print messages
for (AntStatus status : AntStatus.values() ) {
out.println("For status " + status + ", message is: " +
antMessages.get(status));
}
}
shell
public String getDescription() {
switch(this) {
case ROSEWOOD: return "Rosewood back and sides";
case MAHOGANY: return "Mahogany back and sides";
case ZIRICOTE: return "Ziricote back and sides";
case SPRUCE: return "Sitka Spruce top";
case CEDAR: return "Wester Red Cedar top";
case AB_ROSETTE: return "Abalone rosette";
case AB_TOP_BORDER: return "Abalone top border";
case IL_DIAMONDS:
return "Diamonds and squares fretboard inlay";
case IL_DOTS:
return "Small dots fretboard inlay";
default: return "Unknown feature";
}
}
數據庫
private String print(Object... values) {
StringBuilder sb = new StringBuilder();
for (Object o : values) {
sb.append(o.toString())
.append(" ");
}
return sb.toString();
}
編程
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface InProgress { }
api
import static java.lang.System.err;
import static java.lang.System.out;
err.println(msg);
數組
System.out.println("Line %d: %s%n", i++, line);
安全
class SimpleThreadExceptionHandler implements
Thread.UncaughtExceptionHandler {
public void uncaughtException(Thread t, Throwable e) {
System.err.printf("%s: %s at line %d of %s%n",
t.getName(),
e.toString(),
e.getStackTrace()[0].getLineNumber(),
e.getStackTrace()[0].getFileName());
}
服務器
Arrays.sort(myArray);
Arrays.toString(myArray)
Arrays.binarySearch(myArray, 98)
Arrays.deepToString(ticTacToe)
Arrays.deepEquals(ticTacToe, ticTacToe3)
Queue接口與List、Set同一級別,都是繼承了Collection接口。LinkedList實現了Deque接口。
Queue q = new LinkedList(); //採用它來實現queue
Java6開發代號爲Mustang(野馬),於2006-12-11發行。評價:雞肋的版本,有JDBC4.0更新、Complier API、WebSevice支持的增強等更新。
String title = "";
switch (gender) {
case "男":
title = name + " 先生";
break;
case "女":
title = name + " 女士";
break;
default:
title = name;
}
return title;
}
int one_million = 1_000_000;
public void testSequence() {
try {
Integer.parseInt("Hello");
}
catch (NumberFormatException | RuntimeException e) { //使用'|'切割,多個類型,一個對象e
}
}
public void read(String filename) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
StringBuilder builder = new StringBuilder();
String line = null;
while((line=reader.readLine())!=null){
builder.append(line);
builder.append(String.format("%n"));
}
return builder.toString();
}
}
Map<String, List<String>> map = new HashMap<String, List<String>>();
Map<String, List<String>> anagrams = new HashMap<>();
public class ByteBufferUsage {
public void useByteBuffer() {
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.put((byte)1);
buffer.put(new byte[3]);
buffer.putChar('A');
buffer.putFloat(0.0f);
buffer.putLong(10, 100L);
System.out.println(buffer.getChar(4));
System.out.println(buffer.remaining());
}
public void byteOrder() {
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(1);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.getInt(0); //值爲16777216
}
public void compact() {
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.put(new byte[16]);
buffer.flip();
buffer.getInt();
buffer.compact();
int pos = buffer.position();
}
public void viewBuffer() {
ByteBuffer buffer = ByteBuffer.allocate(32);
buffer.putInt(1);
IntBuffer intBuffer = buffer.asIntBuffer();
intBuffer.put(2);
int value = buffer.getInt(); //值爲2
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
ByteBufferUsage bbu = new ByteBufferUsage();
bbu.useByteBuffer();
bbu.byteOrder();
bbu.compact();
bbu.viewBuffer();
}
}
public class FileChannelUsage {
public void openAndWrite() throws IOException {
FileChannel channel = FileChannel.open(Paths.get("my.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(64);
buffer.putChar('A').flip();
channel.write(buffer);
}
public void readWriteAbsolute() throws IOException {
FileChannel channel = FileChannel.open(Paths.get("absolute.txt"), StandardOpenOption.READ, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
ByteBuffer writeBuffer = ByteBuffer.allocate(4).putChar('A').putChar('B');
writeBuffer.flip();
channel.write(writeBuffer, 1024);
ByteBuffer readBuffer = ByteBuffer.allocate(2);
channel.read(readBuffer, 1026);
readBuffer.flip();
char result = readBuffer.getChar(); //值爲'B'
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
FileChannelUsage fcu = new FileChannelUsage();
fcu.openAndWrite();
fcu.readWriteAbsolute();
}
}
public class ThreadPoolManager {
private final ScheduledExecutorService stpe = Executors
.newScheduledThreadPool(2);
private final BlockingQueue<WorkUnit<String>> lbq;
public ThreadPoolManager(BlockingQueue<WorkUnit<String>> lbq_) {
lbq = lbq_;
}
public ScheduledFuture<?> run(QueueReaderTask msgReader) {
msgReader.setQueue(lbq);
return stpe.scheduleAtFixedRate(msgReader, 10, 10, TimeUnit.MILLISECONDS);
}
private void cancel(final ScheduledFuture<?> hndl) {
stpe.schedule(new Runnable() {
public void run() {
hndl.cancel(true);
}
}, 10, TimeUnit.MILLISECONDS);
}
/**
* 使用傳統的反射api
*/
public Method makeReflective() {
Method meth = null;
try {
Class<?>[] argTypes = new Class[]{ScheduledFuture.class};
meth = ThreadPoolManager.class.getDeclaredMethod("cancel", argTypes);
meth.setAccessible(true);
} catch (IllegalArgumentException | NoSuchMethodException
| SecurityException e) {
e.printStackTrace();
}
return meth;
}
/**
* 使用代理類
* @return
*/
public CancelProxy makeProxy() {
return new CancelProxy();
}
/**
* 使用Java7的新api,MethodHandle
* invoke virtual 動態綁定後調用 obj.xxx
* invoke special 靜態綁定後調用 super.xxx
* @return
*/
public MethodHandle makeMh() {
MethodHandle mh;
MethodType desc = MethodType.methodType(void.class, ScheduledFuture.class);
try {
mh = MethodHandles.lookup().findVirtual(ThreadPoolManager.class,
"cancel", desc);
} catch (NoSuchMethodException | IllegalAccessException e) {
throw (AssertionError) new AssertionError().initCause(e);
}
return mh;
}
public static class CancelProxy {
private CancelProxy() {
}
public void invoke(ThreadPoolManager mae_, ScheduledFuture<?> hndl_) {
mae_.cancel(hndl_);
}
}
}
public class ThreadPoolMain {
/**
* 若是被繼承,還能在靜態上下文尋找正確的class
*/
private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
private ThreadPoolManager manager;
public static void main(String[] args) {
ThreadPoolMain main = new ThreadPoolMain();
main.run();
}
private void cancelUsingReflection(ScheduledFuture<?> hndl) {
Method meth = manager.makeReflective();
try {
System.out.println("With Reflection");
meth.invoke(hndl);
} catch (IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
}
}
private void cancelUsingProxy(ScheduledFuture<?> hndl) {
CancelProxy proxy = manager.makeProxy();
System.out.println("With Proxy");
proxy.invoke(manager, hndl);
}
private void cancelUsingMH(ScheduledFuture<?> hndl) {
MethodHandle mh = manager.makeMh();
try {
System.out.println("With Method Handle");
mh.invokeExact(manager, hndl);
} catch (Throwable e) {
e.printStackTrace();
}
}
private void run() {
BlockingQueue<WorkUnit<String>> lbq = new LinkedBlockingQueue<>();
manager = new ThreadPoolManager(lbq);
final QueueReaderTask msgReader = new QueueReaderTask(100) {
@Override
public void doAction(String msg_) {
if (msg_ != null)
System.out.println("Msg recvd: " + msg_);
}
};
ScheduledFuture<?> hndl = manager.run(msgReader);
cancelUsingMH(hndl);
// cancelUsingProxy(hndl);
// cancelUsingReflection(hndl);
}
}
public class PathUsage {
public void usePath() {
Path path1 = Paths.get("folder1", "sub1");
Path path2 = Paths.get("folder2", "sub2");
path1.resolve(path2); //folder1sub1 older2sub2
path1.resolveSibling(path2); //folder1 older2sub2
path1.relativize(path2); //.... older2sub2
path1.subpath(0, 1); //folder1
path1.startsWith(path2); //false
path1.endsWith(path2); //false
Paths.get("folder1/./../folder2/my.text").normalize(); //folder2my.text
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
PathUsage usage = new PathUsage();
usage.usePath();
}
}
public class ListFile {
public void listFiles() throws IOException {
Path path = Paths.get("");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(path, "*.*")) {
for (Path entry: stream) {
//使用entry
System.out.println(entry);
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
ListFile listFile = new ListFile();
listFile.listFiles();
}
}
public class FilesUtils {
public void manipulateFiles() throws IOException {
Path newFile = Files.createFile(Paths.get("new.txt").toAbsolutePath());
List<String> content = new ArrayList<String>();
content.add("Hello");
content.add("World");
Files.write(newFile, content, Charset.forName("UTF-8"));
Files.size(newFile);
byte[] bytes = Files.readAllBytes(newFile);
ByteArrayOutputStream output = new ByteArrayOutputStream();
Files.copy(newFile, output);
Files.delete(newFile);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws IOException {
FilesUtils fu = new FilesUtils();
fu.manipulateFiles();
}
}
public class WatchAndCalculate {
public void calculate() throws IOException, InterruptedException {
WatchService service = FileSystems.getDefault().newWatchService();
Path path = Paths.get("").toAbsolutePath();
path.register(service, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
WatchKey key = service.take();
for (WatchEvent<?> event : key.pollEvents()) {
Path createdPath = (Path) event.context();
createdPath = path.resolve(createdPath);
long size = Files.size(createdPath);
System.out.println(createdPath + " ==> " + size);
}
key.reset();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Throwable {
WatchAndCalculate wc = new WatchAndCalculate();
wc.calculate();
}
}
Java 8可謂是自Java 5以來最具革命性的版本了,她在語言、編譯器、類庫、開發工具以及Java虛擬機等方面都帶來了很多新特性。
Arrays.asList( "p", "k", "u","f", "o", "r","k").forEach( e -> System.out.println( e ) );
public interface DefaultFunctionInterface {
default String defaultFunction() {
return "default function";
}
}
public interface StaticFunctionInterface {
static String staticFunction() {
return "static function";
}
}
private @NotNull String name;
通過4次跳票,歷經曲折的java 9 終於終於在2017年9月21日發佈(距離上個版本足足3年半時間)java 9 提供了超過 150 項新功能特性,包括備受期待的模塊化系統、可交互的 REPL 工具:jshell,JDK 編譯工具,Java 公共 API 和私有代碼,以及安全加強、擴展提高、性能管理改善等。能夠說 Java 9 是一個龐大的系統工程,徹底作了一個總體改變。但本博文只介紹最重要的十大新特性
2018年3月20日,Java 10 正式發佈,這一次沒有跳票。它號稱有109項新特性,包含12個JEP。須要注意的是,本次Java10並非Oracle的官方LTS版本,仍是坐等java11的發佈再考慮在生產中使用
public static void main(String[] args) {
var list = new ArrayList<String>();
list.add("hello,world!");
System.out.println(list);
}
public static void main(String[] args) {
var list = new ArrayList<>();
list.add("hello,world!");
list.add(1);
list.add(1.01);
System.out.println(list);
}
public static void main(String[] args) {
var list = new ArrayList<String>();
list.add("hello,world!");
System.out.println(list);
list = new ArrayList<Integer>(); //編譯報錯
}
public static void main(String[] args) {
//局部變量初始化
var list = new ArrayList<String>();
//for循環內部索引變量
for (var s : list) {
System.out.println(s);
}
//傳統的for循環聲明變量
for (var i = 0; i < list.size(); i++) {
System.out.println(i);
}
}
方法參數全局變量
構造函數參數方法返回類型字段捕獲表達式(或任何其餘類型的變量聲明)
2018年9月26日,Oracle 官方宣佈 Java 11 正式發佈。這是 Java 大版本週期變化後的第一個長期支持版本(LTS版本,Long-Term-Support,持續支持到2026年9月),很是值得關注。Java11 帶來了 ZGC、Http Client 等重要特性,一共包含 17 個 JEP(JDK Enhancement Proposals,JDK 加強提案)。
var list = List.of("Java", "Python", "C");
var copy = List.copyOf(list);
System.out.println(list == copy); // true
var list = new ArrayList<String>();
var copy = List.copyOf(list);
System.out.println(list == copy); // false
static <E> List<E> of(E... elements) {
switch (elements.length) { // implicit null check of elements
case 0:
return ImmutableCollections.emptyList();
case 1:
return new ImmutableCollections.List12<>(elements[0]);
case 2:
return new ImmutableCollections.List12<>(elements[0], elements[1]);
default:
return new ImmutableCollections.ListN<>(elements);
}
}
static <E> List<E> copyOf(Collection<? extends E> coll) {
return ImmutableCollections.listCopy(coll);
}
static <E> List<E> listCopy(Collection<? extends E> coll) {
if (coll instanceof AbstractImmutableList && coll.getClass() != SubList.class) {
return (List<E>)coll;
} else {
return (List<E>)List.of(coll.toArray());
}
}
注意:使用of和copyOf建立的集合爲不可變集合,不能進行添加、刪除、替換、排序等操做,否則會報 java.lang.UnsupportedOperationException 異常。
public static void main(String[] args) {
Set<String> names = Set.of("Fred", "Wilma", "Barney", "Betty");
//JDK11以前咱們只能這麼寫
System.out.println(Arrays.toString(names.toArray(new String[names.size()])));
//JDK11以後 能夠直接這麼寫了
System.out.println(Arrays.toString(names.toArray(size -> new String[size])));
System.out.println(Arrays.toString(names.toArray(String[]::new)));
}
public static void main(String[] args) {
Set<String> names = Set.of("Fred", "Wilma", "Barney", "Betty");
//JDK11以前咱們只能這麼寫
System.out.println(Arrays.toString(names.toArray(new String[names.size()])));
//JDK11以後 能夠直接這麼寫了
System.out.println(Arrays.toString(names.toArray(size -> new String[size])));
System.out.println(Arrays.toString(names.toArray(String[]::new)));
}
Stream.ofNullable(null).count(); // 0
//JDK8木有ofNullable方法哦
/**
* @since 9
*/
public static<T> Stream<T> ofNullable(T t) {
return t == null ? Stream.empty()
: StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
Stream.of(1, 2, 3, 2, 1)
.takeWhile(n -> n < 3)
.collect(Collectors.toList()); // [1, 2]
Stream.of(1, 2, 3, 2, 1)
.dropWhile(n -> n < 3)
.collect(Collectors.toList()); // [3, 2, 1]
public static void main(String[] args) {
// 這構造的是無限流 JDK8開始
Stream.iterate(0, (x) -> x + 1);
// 這構造的是小於10就結束的流 JDK9開始
Stream.iterate(0, x -> x < 10, x -> x + 1);
}
Optional.of("javastack").orElseThrow(); // javastack
Optional.of("javastack").stream().count(); // 1
Optional.ofNullable(null)
.or(() -> Optional.of("javastack"))
.get(); // javastac
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("javastack.txt");
var javastack = File.createTempFile("javastack2", "txt");
try (var outputStream = new FileOutputStream(javastack)) {
inputStream.transferTo(outputStream);
}
在java9及10被標記incubator的模塊jdk.incubator.httpclient,在java11被標記爲正式,改成java.net.http模塊。這是 Java 9 開始引入的一個處理 HTTP 請求的的孵化 HTTP Client API,該 API 支持同步和異步,而在 Java 11 中已經爲正式可用狀態,你能夠在 java.net 包中找到這個 API。
// 編譯
javac Javastack.java
// 運行
java Javastack
java Javastack.java
從java11版本開始,再也不單獨發佈JRE或者Server JRE版本了,有須要的能夠本身經過jlink去定製runtime image
更多技術資訊:gzitcast