import java.util.Optional;
publicclassOptionalDemo {
publicstaticvoidmain(String[] args) { //创建Optional实例,也可以通过方法返回值得到。 Optional<String> name = Optional.of("Sanaulla");
//创建没有值的Optional实例,例如值为'null' Optional empty = Optional.ofNullable(null);
//isPresent方法用来检查Optional实例是否有值。 if(name.isPresent()) { //调用get()返回Optional值。 System.out.println(name.get()); }
try{ //在Optional实例上调用get()抛出NoSuchElementException。 System.out.println(empty.get()); } catch(NoSuchElementException ex) { System.out.println(ex.getMessage()); }
//ifPresent方法接受lambda表达式参数。 //如果Optional值不为空,lambda表达式会处理并在其上执行操作。 name.ifPresent((value) -> { System.out.println("The length of the value is: "+ value.length()); });
//如果有值orElse方法会返回Optional实例,否则返回传入的错误信息。 System.out.println(empty.orElse("There is no value present!")); System.out.println(name.orElse("There is some value!"));
//orElseGet与orElse类似,区别在于传入的默认值。 //orElseGet接受lambda表达式生成默认值。 System.out.println(empty.orElseGet(() -> "Default Value")); System.out.println(name.orElseGet(() -> "Default Value"));
try{ //orElseThrow与orElse方法类似,区别在于返回值。 //orElseThrow抛出由传入的lambda表达式/方法生成异常。 empty.orElseThrow(ValueAbsentException::new); } catch(Throwable ex) { System.out.println(ex.getMessage()); }
//map方法通过传入的lambda表达式修改Optonal实例默认值。 //lambda表达式返回值会包装为Optional实例。 Optional<String> upperName = name.map((value) -> value.toUpperCase()); System.out.println(upperName.orElse("No value found"));
//flatMap与map(Funtion)非常相似,区别在于lambda表达式的返回值。 //map方法的lambda表达式返回值可以是任何类型,但是返回值会包装成Optional实例。 //但是flatMap方法的lambda返回值总是Optional类型。 upperName = name.flatMap((value) -> Optional.of(value.toUpperCase())); System.out.println(upperName.orElse("No value found"));
//filter方法检查Optiona值是否满足给定条件。 //如果满足返回Optional实例值,否则返回空Optional。 Optional<String> longName = name.filter((value) -> value.length() > 6); System.out.println(longName.orElse("The name is less than 6 characters"));
//另一个示例,Optional值不满足给定条件。 Optional<String> anotherName = Optional.of("Sana"); Optional<String> shortName = anotherName.filter((value) -> value.length() > 6); System.out.println(shortName.orElse("The name is less than 6 characters"));
}
} |
上述代码输出如下:
1 2 3 4 5 6 7 8 9 10 11 12 |
Sanaulla No value present The length of the value is: 8 There is no value present! Sanaulla Default Value Sanaulla No value present inthe Optional instance SANAULLA SANAULLA Sanaulla The name is lessthan 6 characters |
二:AtomicInteger:AtomicInteger是一个提供原子操作的Integer类,通过线程安全的方式操作加减。AtomicInteger提供原子操作来进行Integer的使用,因此十分适合高并发情况下的使用。
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicTest {
staticlong randomTime() {
return (long) (Math.random() * 1000);
}
publicstatic void main(String[] args) {
// 阻塞队列,能容纳100个文件
final BlockingQueue<File> queue = newLinkedBlockingQueue<File>(100);
// 线程池
final ExecutorService exec = Executors.newFixedThreadPool(5);
final File root = new File("D:\\ISO");
// 完成标志
final File exitFile = new File("");
// 原子整型,读个数
// AtomicInteger可以在并发情况下达到原子化更新,避免使用了synchronized,而且性能非常高。
final AtomicInteger rc = new AtomicInteger();
// 原子整型,写个数
final AtomicInteger wc = new AtomicInteger();
// 读线程
Runnable read = new Runnable() {
public void run() {
scanFile(root);
scanFile(exitFile);
}
public void scanFile(File file) {
if (file.isDirectory()) {
File[] files =file.listFiles(new FileFilter() {
public boolean accept(Filepathname) {
returnpathname.isDirectory() || pathname.getPath().endsWith(".iso");
}
});
for (File one : files)
scanFile(one);
} else {
try {
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index =rc.incrementAndGet();
System.out.println("Read0:" + index + " " + file.getPath());
// 添加到阻塞队列中
queue.put(file);
} catch(InterruptedException e) {
}
}
}
};
// submit方法提交一个 Runnable 任务用于执行,并返回一个表示该任务的 Future。
exec.submit(read);
// 四个写线程
for (int index = 0; index < 4; index++) {
// write thread
final int num = index;
Runnable write = new Runnable() {
String threadName = "Write"+ num;
public void run() {
while (true) {
try {
Thread.sleep(randomTime());
// 原子整型的incrementAndGet方法,以原子方式将当前值加 1,返回更新的值
int index =wc.incrementAndGet();
// 获取并移除此队列的头部,在元素变得可用之前一直等待(如果有必要)。
File file =queue.take();
// 队列已经无对象
if (file ==exitFile) {
// 再次添加"标志",以让其他线程正常退出
queue.put(exitFile);
break;
}
System.out.println(threadName + ":" + index + " " + file.getPath());
} catch(InterruptedException e) {
}
}
}
};
exec.submit(write);
}
exec.shutdown();
}
}
三:Guava工具类: Guava是对Java API的补充,对Java开发中常用功能进行更优雅的实现,使得编码更加轻松,代码容易理解。Guava使用了多种设计模式。