Update to latest
This commit is contained in:
parent
e7291af6ec
commit
a40b9896ba
@ -14,6 +14,7 @@
|
||||
<include name="**/*.tmp" />
|
||||
<include name="**/*.xml" />
|
||||
<include name="**/*.out" />
|
||||
<include name="**/*.err" />
|
||||
<include name="**/*.dat" />
|
||||
<include name="**/*.log" />
|
||||
<include name="**/failures" />
|
||||
|
@ -34,6 +34,11 @@
|
||||
timeout="@{timeOut}"
|
||||
output="${antoutput}" append="true">
|
||||
<arg line="@{arguments}"/>
|
||||
<redirector
|
||||
output="@{cls}.out"
|
||||
error="@{cls}.err"
|
||||
createemptyfiles="false"
|
||||
append="false" />
|
||||
</java>
|
||||
<echo file="${antoutput}" append="true">[${chapter}] Finished: java @{cls} @{arguments} </echo>
|
||||
<echo file="${antoutput}" append="true">@{msg} </echo>
|
||||
@ -102,6 +107,12 @@
|
||||
<compilerarg value="-Xmaxerrs"/>
|
||||
<compilerarg value="10"/>
|
||||
</javac>
|
||||
<javac includeantruntime="false"
|
||||
classpath="${java.class.path};${basedir};${basedir}/.."
|
||||
srcdir="${basedir}/../polymorphism/music/">
|
||||
<compilerarg value="-Xmaxerrs"/>
|
||||
<compilerarg value="10"/>
|
||||
</javac>
|
||||
</target>
|
||||
|
||||
<target
|
||||
@ -143,4 +154,13 @@
|
||||
<echo file="${antoutput}" append="true" message="Build '${chapter}' succeeded "/>
|
||||
</target>
|
||||
|
||||
<target
|
||||
depends="base"
|
||||
description="Verify output; requires Python 3.5"
|
||||
name="verify">
|
||||
<exec dir="${basedir}" executable="python" failonerror="true">
|
||||
<arg line="../verify_output.py" />
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
</project>
|
||||
|
@ -18,12 +18,14 @@ public class AtUnitComposition {
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
OSExecute.command(
|
||||
"java com.mindviewinc.atunit.AtUnit AtUnitComposition");
|
||||
"java com.mindviewinc.atunit.AtUnit " +
|
||||
" AtUnitComposition");
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
annotations.AtUnitComposition
|
||||
. _methodOne
|
||||
. _methodTwo This is methodTwo
|
||||
|
||||
OK (2 tests)
|
||||
*/
|
||||
|
@ -30,11 +30,13 @@ public class AtUnitExample1 {
|
||||
/* Output:
|
||||
annotations.AtUnitExample1
|
||||
. anotherDisappointment (failed)
|
||||
. failureTest (failed)
|
||||
. methodOneTest
|
||||
. m2 This is methodTwo
|
||||
. failureTest (failed)
|
||||
. m3
|
||||
. m2 This is methodTwo
|
||||
|
||||
(5 tests)
|
||||
|
||||
>>> 2 FAILURES <<<
|
||||
annotations.AtUnitExample1: anotherDisappointment
|
||||
annotations.AtUnitExample1: failureTest
|
||||
|
@ -40,12 +40,14 @@ annotations.AtUnitExample2
|
||||
. assertFailureExample java.lang.AssertionError: What a
|
||||
surprise!
|
||||
(failed)
|
||||
. assertExample
|
||||
. assertAndReturn This is methodTwo
|
||||
|
||||
. exceptionExample java.io.FileNotFoundException:
|
||||
nofile.txt (The system cannot find the file specified)
|
||||
(failed)
|
||||
. assertAndReturn This is methodTwo
|
||||
. assertExample
|
||||
(4 tests)
|
||||
|
||||
>>> 2 FAILURES <<<
|
||||
annotations.AtUnitExample2: assertFailureExample
|
||||
annotations.AtUnitExample2: exceptionExample
|
||||
|
@ -32,8 +32,9 @@ public class AtUnitExample3 {
|
||||
}
|
||||
/* Output:
|
||||
annotations.AtUnitExample3
|
||||
. methodOneTest
|
||||
. initialization
|
||||
. methodOneTest
|
||||
. m2 This is methodTwo
|
||||
|
||||
OK (3 tests)
|
||||
*/
|
||||
|
@ -64,10 +64,18 @@ public class AtUnitExample4 {
|
||||
/* Output:
|
||||
starting
|
||||
annotations.AtUnitExample4
|
||||
. scramble1 'All'
|
||||
lAl
|
||||
. scramble2 'brontosauruses'
|
||||
tsaeborornussu
|
||||
. words 'are'
|
||||
OK (3 tests)
|
||||
. words 'All'
|
||||
(failed)
|
||||
. scramble1 'brontosauruses'
|
||||
ntsaueorosurbs
|
||||
(failed)
|
||||
. scramble2 'are'
|
||||
are
|
||||
(failed)
|
||||
(3 tests)
|
||||
|
||||
>>> 3 FAILURES <<<
|
||||
annotations.AtUnitExample4: words
|
||||
annotations.AtUnitExample4: scramble1
|
||||
annotations.AtUnitExample4: scramble2
|
||||
*/
|
||||
|
@ -47,11 +47,11 @@ public class AtUnitExample5 {
|
||||
}
|
||||
/* Output:
|
||||
annotations.AtUnitExample5
|
||||
. test3
|
||||
Running cleanup
|
||||
. test1
|
||||
Running cleanup
|
||||
. test2
|
||||
Running cleanup
|
||||
. test3
|
||||
Running cleanup
|
||||
OK (3 tests)
|
||||
*/
|
||||
|
@ -12,14 +12,16 @@ public class AtUnitExternalTest extends AtUnitExample1 {
|
||||
return methodOne().equals("This is methodOne");
|
||||
}
|
||||
@Test boolean _methodTwo() { return methodTwo() == 2; }
|
||||
public static void main(String[] args) throws Exception {
|
||||
public static void main(String[] args) throws Exception{
|
||||
OSExecute.command(
|
||||
"java com.mindviewinc.atunit.AtUnit AtUnitExternalTest");
|
||||
"java com.mindviewinc.atunit.AtUnit " +
|
||||
"AtUnitExternalTest");
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
annotations.AtUnitExternalTest
|
||||
. _methodTwo This is methodTwo
|
||||
|
||||
. _methodOne
|
||||
OK (2 tests)
|
||||
*/
|
||||
|
@ -29,7 +29,7 @@ public class HashSetTest {
|
||||
/* Output:
|
||||
annotations.HashSetTest
|
||||
. initialization
|
||||
. _remove
|
||||
. _contains
|
||||
. _remove
|
||||
OK (3 tests)
|
||||
*/
|
||||
|
@ -28,13 +28,14 @@ public class StackLStringTest extends StackL<String> {
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
OSExecute.command(
|
||||
"java com.mindviewinc.atunit.AtUnit StackLStringTest");
|
||||
"java com.mindviewinc.atunit.AtUnit " +
|
||||
"StackLStringTest");
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
annotations.StackLStringTest
|
||||
. _push
|
||||
. _top
|
||||
. _push
|
||||
. _pop
|
||||
OK (3 tests)
|
||||
*/
|
||||
|
@ -14,12 +14,14 @@ public class ArraySearching {
|
||||
int[] a = ConvertTo.primitive(
|
||||
Generated.array(new Integer[25], gen));
|
||||
Arrays.sort(a);
|
||||
System.out.println("Sorted array: " + Arrays.toString(a));
|
||||
System.out.println(
|
||||
"Sorted array: " + Arrays.toString(a));
|
||||
while(true) {
|
||||
int r = gen.get();
|
||||
int location = Arrays.binarySearch(a, r);
|
||||
if(location >= 0) {
|
||||
System.out.println("Location of " + r + " is " + location +
|
||||
System.out.println(
|
||||
"Location of " + r + " is " + location +
|
||||
", a[" + location + "] = " + a[location]);
|
||||
break; // Out of while loop
|
||||
}
|
||||
|
@ -10,13 +10,17 @@ public class StringSorting {
|
||||
public static void main(String[] args) {
|
||||
String[] sa = Generated.array(new String[20],
|
||||
new RandomSupplier.String(5));
|
||||
System.out.println("Before sort: " + Arrays.toString(sa));
|
||||
System.out.println(
|
||||
"Before sort: " + Arrays.toString(sa));
|
||||
Arrays.sort(sa);
|
||||
System.out.println("After sort: " + Arrays.toString(sa));
|
||||
System.out.println(
|
||||
"After sort: " + Arrays.toString(sa));
|
||||
Arrays.sort(sa, Collections.reverseOrder());
|
||||
System.out.println("Reverse sort: " + Arrays.toString(sa));
|
||||
System.out.println(
|
||||
"Reverse sort: " + Arrays.toString(sa));
|
||||
Arrays.sort(sa, String.CASE_INSENSITIVE_ORDER);
|
||||
System.out.println("Case-insensitive sort: " + Arrays.toString(sa));
|
||||
System.out.println(
|
||||
"Case-insensitive sort: " + Arrays.toString(sa));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
|
11
build.xml
11
build.xml
@ -85,12 +85,11 @@
|
||||
<echo message="Errors occurred. See errors.txt for information."/>
|
||||
</target>
|
||||
|
||||
<target name="verify" depends="build"
|
||||
description="Verifies comment output; requires Python 2.3 or newer">
|
||||
<echo message="run program by hand:"/>
|
||||
<echo message="python OutputVerifier.py"/>
|
||||
<echo message="Or:"/>
|
||||
<echo message="py -2 OutputVerifier.py"/>
|
||||
<target name="verify"
|
||||
description="Verify output; requires Python 3.5">
|
||||
<exec dir="${basedir}" executable="python" failonerror="true">
|
||||
<arg line="verify_output.py" />
|
||||
</exec>
|
||||
</target>
|
||||
|
||||
<target name="findbugs" depends="build"
|
||||
|
@ -68,11 +68,13 @@ public class ClassNameFinder {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if(args.length > 0) {
|
||||
for(String arg : args)
|
||||
System.out.println(thisClass(BinaryFile.read(new File(arg))));
|
||||
System.out.println(
|
||||
thisClass(BinaryFile.read(new File(arg))));
|
||||
} else
|
||||
// Walk the entire tree: <* Use NIO2 here *>
|
||||
for(File klass : Directory.walk(".", ".*\\.class"))
|
||||
System.out.println(thisClass(BinaryFile.read(klass)));
|
||||
System.out.println(
|
||||
thisClass(BinaryFile.read(klass)));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
|
@ -33,7 +33,8 @@ public class ZipCompress {
|
||||
}
|
||||
}
|
||||
// Checksum valid only after the file is closed!
|
||||
System.out.println("Checksum: " + csum.getChecksum().getValue());
|
||||
System.out.println(
|
||||
"Checksum: " + csum.getChecksum().getValue());
|
||||
// Now extract the files:
|
||||
System.out.println("Reading file");
|
||||
FileInputStream fi = new FileInputStream("test.zip");
|
||||
@ -50,7 +51,8 @@ public class ZipCompress {
|
||||
System.out.write(x);
|
||||
}
|
||||
if(args.length == 1)
|
||||
System.out.println("Checksum: "+csumi.getChecksum().getValue());
|
||||
System.out.println(
|
||||
"Checksum: "+csumi.getChecksum().getValue());
|
||||
}
|
||||
// Alternative way to open and read Zip files:
|
||||
ZipFile zf = new ZipFile("test.zip");
|
||||
|
@ -127,7 +127,8 @@ abstract class Robot implements Runnable {
|
||||
powerDown();
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("Exiting " + this + " via interrupt");
|
||||
System.out.println(
|
||||
"Exiting " + this + " via interrupt");
|
||||
} catch(BrokenBarrierException e) {
|
||||
// This one we want to know about
|
||||
throw new RuntimeException(e);
|
||||
|
@ -21,11 +21,13 @@ public class CloseResource {
|
||||
System.out.println("Shutting down all threads");
|
||||
exec.shutdownNow();
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
System.out.println("Closing " + socketInput.getClass().getName());
|
||||
System.out.println(
|
||||
"Closing " + socketInput.getClass().getName());
|
||||
socketInput.close(); // Releases blocked thread
|
||||
}
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
System.out.println("Closing " + System.in.getClass().getName());
|
||||
System.out.println(
|
||||
"Closing " + System.in.getClass().getName());
|
||||
System.in.close(); // Releases blocked thread
|
||||
}
|
||||
}
|
||||
|
@ -45,7 +45,8 @@ class WaitingTask implements Runnable {
|
||||
public void run() {
|
||||
try {
|
||||
latch.await();
|
||||
System.out.println("Latch barrier passed for " + this);
|
||||
System.out.println(
|
||||
"Latch barrier passed for " + this);
|
||||
} catch(InterruptedException ex) {
|
||||
System.out.println(this + " interrupted");
|
||||
}
|
||||
|
@ -12,7 +12,8 @@ public class DaemonFromFactory implements Runnable {
|
||||
try {
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
System.out.println(Thread.currentThread() + " " + this);
|
||||
System.out.println(
|
||||
Thread.currentThread() + " " + this);
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("Interrupted");
|
||||
|
@ -35,7 +35,8 @@ public class Daemons {
|
||||
Thread d = new Thread(new Daemon());
|
||||
d.setDaemon(true);
|
||||
d.start();
|
||||
System.out.print("d.isDaemon() = " + d.isDaemon() + ", ");
|
||||
System.out.print(
|
||||
"d.isDaemon() = " + d.isDaemon() + ", ");
|
||||
// Allow the daemon threads to
|
||||
// finish their startup processes:
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
|
@ -12,7 +12,8 @@ class ADaemon implements Runnable {
|
||||
System.out.println("Starting ADaemon");
|
||||
TimeUnit.SECONDS.sleep(1);
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("Exiting via InterruptedException");
|
||||
System.out.println(
|
||||
"Exiting via InterruptedException");
|
||||
} finally {
|
||||
System.out.println("ADaemon finally clause");
|
||||
}
|
||||
|
@ -34,7 +34,8 @@ public class FastSimulation {
|
||||
// Policy here to deal with failure. Here, we
|
||||
// just report it and ignore it; our model
|
||||
// will eventually deal with it.
|
||||
System.out.println("Old value changed from " + oldvalue);
|
||||
System.out.println(
|
||||
"Old value changed from " + oldvalue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -64,7 +64,8 @@ public class HorseRace {
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(pause);
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("barrier-action sleep interrupted");
|
||||
System.out.println(
|
||||
"barrier-action sleep interrupted");
|
||||
}
|
||||
});
|
||||
for(int i = 0; i < nHorses; i++) {
|
||||
|
@ -64,9 +64,11 @@ public class Interrupting {
|
||||
static void test(Runnable r) throws InterruptedException{
|
||||
Future<?> f = exec.submit(r);
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
System.out.println("Interrupting " + r.getClass().getName());
|
||||
System.out.println(
|
||||
"Interrupting " + r.getClass().getName());
|
||||
f.cancel(true); // Interrupts if running
|
||||
System.out.println("Interrupt sent to " + r.getClass().getName());
|
||||
System.out.println(
|
||||
"Interrupt sent to " + r.getClass().getName());
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
test(new SleepBlocked());
|
||||
|
@ -19,7 +19,8 @@ class BlockedMutex {
|
||||
lock.lockInterruptibly(); // Special call
|
||||
System.out.println("lock acquired in f()");
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("Interrupted from lock acquisition in f()");
|
||||
System.out.println(
|
||||
"Interrupted from lock acquisition in f()");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -38,7 +38,8 @@ class Blocked3 implements Runnable {
|
||||
// A time-consuming, non-blocking operation:
|
||||
for(int i = 1; i < 2500000; i++)
|
||||
d += (Math.PI + Math.E) / d;
|
||||
System.out.println("Finished time-consuming operation");
|
||||
System.out.println(
|
||||
"Finished time-consuming operation");
|
||||
} finally {
|
||||
n2.cleanup();
|
||||
}
|
||||
@ -48,7 +49,8 @@ class Blocked3 implements Runnable {
|
||||
}
|
||||
System.out.println("Exiting via while() test");
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("Exiting via InterruptedException");
|
||||
System.out.println(
|
||||
"Exiting via InterruptedException");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -56,7 +58,8 @@ class Blocked3 implements Runnable {
|
||||
public class InterruptingIdiom {
|
||||
public static void main(String[] args) throws Exception {
|
||||
if(args.length != 1) {
|
||||
System.out.println("usage: java InterruptingIdiom delay-in-mS");
|
||||
System.out.println(
|
||||
"usage: java InterruptingIdiom delay-in-mS");
|
||||
System.exit(1);
|
||||
}
|
||||
Thread t = new Thread(new Blocked3());
|
||||
|
@ -7,13 +7,15 @@
|
||||
public class MultiLock {
|
||||
public synchronized void f1(int count) {
|
||||
if(count-- > 0) {
|
||||
System.out.println("f1() calling f2() with count " + count);
|
||||
System.out.println(
|
||||
"f1() calling f2() with count " + count);
|
||||
f2(count);
|
||||
}
|
||||
}
|
||||
public synchronized void f2(int count) {
|
||||
if(count-- > 0) {
|
||||
System.out.println("f2() calling f1() with count " + count);
|
||||
System.out.println(
|
||||
"f2() calling f1() with count " + count);
|
||||
f1(count);
|
||||
}
|
||||
}
|
||||
|
@ -40,7 +40,8 @@ class Entrance implements Runnable {
|
||||
synchronized(this) {
|
||||
++number;
|
||||
}
|
||||
System.out.println(this + " Total: " + count.increment());
|
||||
System.out.println(
|
||||
this + " Total: " + count.increment());
|
||||
try {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
} catch(InterruptedException e) {
|
||||
@ -76,8 +77,10 @@ public class OrnamentalGarden {
|
||||
exec.shutdown();
|
||||
if(!exec.awaitTermination(250, TimeUnit.MILLISECONDS))
|
||||
System.out.println("Some tasks were not terminated!");
|
||||
System.out.println("Total: " + Entrance.getTotalCount());
|
||||
System.out.println("Sum of Entrances: " + Entrance.sumEntrances());
|
||||
System.out.println(
|
||||
"Total: " + Entrance.getTotalCount());
|
||||
System.out.println(
|
||||
"Sum of Entrances: " + Entrance.sumEntrances());
|
||||
}
|
||||
}
|
||||
/* Output: (First and last 10 Lines)
|
||||
|
@ -41,7 +41,8 @@ public class Philosopher implements Runnable {
|
||||
left.drop();
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println(this + " " + "exiting via interrupt");
|
||||
System.out.println(
|
||||
this + " " + "exiting via interrupt");
|
||||
}
|
||||
}
|
||||
@Override
|
||||
|
@ -23,7 +23,8 @@ class WaitPerson implements Runnable {
|
||||
while(restaurant.meal == null)
|
||||
wait(); // ... for the chef to produce a meal
|
||||
}
|
||||
System.out.println("Waitperson got " + restaurant.meal);
|
||||
System.out.println(
|
||||
"Waitperson got " + restaurant.meal);
|
||||
synchronized(restaurant.chef) {
|
||||
restaurant.meal = null;
|
||||
restaurant.chef.notifyAll(); // Ready for another
|
||||
|
@ -11,7 +11,8 @@ public class SimpleDaemons implements Runnable {
|
||||
try {
|
||||
while(true) {
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
System.out.println(Thread.currentThread() + " " + this);
|
||||
System.out.println(
|
||||
Thread.currentThread() + " " + this);
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println("sleep() interrupted");
|
||||
|
@ -13,7 +13,7 @@ public class SleepingTask extends LiftOff {
|
||||
System.out.print(status());
|
||||
// Old-style:
|
||||
// Thread.sleep(100);
|
||||
// Java 5/6-style:
|
||||
// Modern style:
|
||||
TimeUnit.MILLISECONDS.sleep(100);
|
||||
}
|
||||
} catch(InterruptedException e) {
|
||||
|
@ -73,7 +73,8 @@ abstract class Accumulator {
|
||||
System.out.printf("%-13s: %13d\n", id, duration);
|
||||
}
|
||||
public void report(Accumulator acc2) {
|
||||
System.out.printf("%-22s: %.2f\n", this.id + "/" + acc2.id,
|
||||
System.out.printf(
|
||||
"%-22s: %.2f\n", this.id + "/" + acc2.id,
|
||||
(double)this.duration/(double)acc2.duration);
|
||||
}
|
||||
}
|
||||
@ -134,7 +135,8 @@ class AtomicTest extends Accumulator {
|
||||
public synchronized long read() { return value.get(); }
|
||||
@Override
|
||||
public void report(Accumulator acc2) {
|
||||
System.out.printf("%-22s: %.2f\n", "synch/(Atomic-synch)",
|
||||
System.out.printf(
|
||||
"%-22s: %.2f\n", "synch/(Atomic-synch)",
|
||||
(double)acc2.duration/
|
||||
((double)this.duration - (double)acc2.duration));
|
||||
}
|
||||
@ -146,7 +148,8 @@ public class SynchronizationComparisons {
|
||||
static AtomicTest atomic = new AtomicTest();
|
||||
static void test() {
|
||||
System.out.println("============================");
|
||||
System.out.printf("%-12s : %13d\n", "Cycles", Accumulator.cycles);
|
||||
System.out.printf(
|
||||
"%-12s : %13d\n", "Cycles", Accumulator.cycles);
|
||||
synch.timedTest();
|
||||
lock.timedTest();
|
||||
atomic.timedTest();
|
||||
|
@ -66,7 +66,8 @@ class Customer implements Runnable {
|
||||
try {
|
||||
waitPerson.placeOrder(this, food);
|
||||
// Blocks until course is delivered:
|
||||
System.out.println(this + "eating " + placeSetting.take());
|
||||
System.out.println(
|
||||
this + "eating " + placeSetting.take());
|
||||
} catch(InterruptedException e) {
|
||||
System.out.println(this + "waiting for " +
|
||||
course + " interrupted");
|
||||
|
@ -11,13 +11,17 @@ public class LinkedListFeatures {
|
||||
new LinkedList<>(Pets.arrayList(5));
|
||||
System.out.println(pets);
|
||||
// Identical:
|
||||
System.out.println("pets.getFirst(): " + pets.getFirst());
|
||||
System.out.println("pets.element(): " + pets.element());
|
||||
System.out.println(
|
||||
"pets.getFirst(): " + pets.getFirst());
|
||||
System.out.println(
|
||||
"pets.element(): " + pets.element());
|
||||
// Only differs in empty-list behavior:
|
||||
System.out.println("pets.peek(): " + pets.peek());
|
||||
// Identical; remove and return the first element:
|
||||
System.out.println("pets.remove(): " + pets.remove());
|
||||
System.out.println("pets.removeFirst(): " + pets.removeFirst());
|
||||
System.out.println(
|
||||
"pets.remove(): " + pets.remove());
|
||||
System.out.println(
|
||||
"pets.removeFirst(): " + pets.removeFirst());
|
||||
// Only differs in empty-list behavior:
|
||||
System.out.println("pets.poll(): " + pets.poll());
|
||||
System.out.println(pets);
|
||||
@ -29,7 +33,8 @@ public class LinkedListFeatures {
|
||||
System.out.println("After add(): " + pets);
|
||||
pets.addLast(new Hamster());
|
||||
System.out.println("After addLast(): " + pets);
|
||||
System.out.println("pets.removeLast(): " + pets.removeLast());
|
||||
System.out.println(
|
||||
"pets.removeLast(): " + pets.removeLast());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
|
@ -14,12 +14,15 @@ public class SetOperations {
|
||||
System.out.println("N: " + set1.contains("N"));
|
||||
Set<String> set2 = new HashSet<>();
|
||||
Collections.addAll(set2, "H I J K L".split(" "));
|
||||
System.out.println("set2 in set1: " + set1.containsAll(set2));
|
||||
System.out.println(
|
||||
"set2 in set1: " + set1.containsAll(set2));
|
||||
set1.remove("H");
|
||||
System.out.println("set1: " + set1);
|
||||
System.out.println("set2 in set1: " + set1.containsAll(set2));
|
||||
System.out.println(
|
||||
"set2 in set1: " + set1.containsAll(set2));
|
||||
set1.removeAll(set2);
|
||||
System.out.println("set2 removed from set1: " + set1);
|
||||
System.out.println(
|
||||
"set2 removed from set1: " + set1);
|
||||
Collections.addAll(set1, "X Y Z".split(" "));
|
||||
System.out.println("'X Y Z' added to set1: " + set1);
|
||||
}
|
||||
|
@ -20,8 +20,10 @@ public class CollectionMethods {
|
||||
// Find max and min elements; this means
|
||||
// different things depending on the way
|
||||
// the Comparable interface is implemented:
|
||||
System.out.println("Collections.max(c) = " + Collections.max(c));
|
||||
System.out.println("Collections.min(c) = " + Collections.min(c));
|
||||
System.out.println(
|
||||
"Collections.max(c) = " + Collections.max(c));
|
||||
System.out.println(
|
||||
"Collections.min(c) = " + Collections.min(c));
|
||||
// Add a Collection to another Collection
|
||||
Collection<String> c2 = new ArrayList<>();
|
||||
c2.addAll(Countries.names(6));
|
||||
@ -39,9 +41,11 @@ public class CollectionMethods {
|
||||
System.out.println(c);
|
||||
// Is an element in this Collection?
|
||||
String val = Countries.DATA[3][0];
|
||||
System.out.println("c.contains(" + val + ") = " + c.contains(val));
|
||||
System.out.println(
|
||||
"c.contains(" + val + ") = " + c.contains(val));
|
||||
// Is a Collection in this Collection?
|
||||
System.out.println("c.containsAll(c2) = " + c.containsAll(c2));
|
||||
System.out.println(
|
||||
"c.containsAll(c2) = " + c.containsAll(c2));
|
||||
Collection<String> c3 =
|
||||
((List<String>)c).subList(3, 5);
|
||||
// Keep all the elements that are in both
|
||||
|
@ -24,14 +24,16 @@ public class ListSortSearch {
|
||||
System.out.println("Sorted: " + list);
|
||||
String key = list.get(7);
|
||||
int index = Collections.binarySearch(list, key);
|
||||
System.out.println("Location of " + key + " is " + index +
|
||||
System.out.println(
|
||||
"Location of " + key + " is " + index +
|
||||
", list.get(" + index + ") = " + list.get(index));
|
||||
Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
|
||||
System.out.println("Case-insensitive sorted: " + list);
|
||||
key = list.get(7);
|
||||
index = Collections.binarySearch(list, key,
|
||||
String.CASE_INSENSITIVE_ORDER);
|
||||
System.out.println("Location of " + key + " is " + index +
|
||||
System.out.println(
|
||||
"Location of " + key + " is " + index +
|
||||
", list.get(" + index + ") = " + list.get(index));
|
||||
}
|
||||
}
|
||||
|
@ -35,10 +35,12 @@ public class MapDataTest {
|
||||
// Pair Supplier:
|
||||
System.out.println(MapData.map(new Letters(), 11));
|
||||
// Two separate generators:
|
||||
System.out.println(MapData.map(new CountingSupplier.Character(),
|
||||
System.out.println(
|
||||
MapData.map(new CountingSupplier.Character(),
|
||||
new RandomSupplier.String(3), 8));
|
||||
// A key Supplier and a single value:
|
||||
System.out.println(MapData.map(new CountingSupplier.Character(),
|
||||
System.out.println(
|
||||
MapData.map(new CountingSupplier.Character(),
|
||||
"Value", 6));
|
||||
// An Iterable and a value Supplier:
|
||||
System.out.println(MapData.map(new Letters(),
|
||||
|
@ -11,7 +11,8 @@ public class Maps {
|
||||
public static void printKeys(Map<Integer,String> map) {
|
||||
System.out.print("Size = " + map.size() + ", ");
|
||||
System.out.print("Keys: ");
|
||||
System.out.println(map.keySet()); // Produce a Set of the keys
|
||||
// Produce a Set of the keys:
|
||||
System.out.println(map.keySet());
|
||||
}
|
||||
public static void test(Map<Integer,String> map) {
|
||||
System.out.println(map.getClass().getSimpleName());
|
||||
@ -23,7 +24,8 @@ public class Maps {
|
||||
System.out.print("Values: ");
|
||||
System.out.println(map.values());
|
||||
System.out.println(map);
|
||||
System.out.println("map.containsKey(11): " + map.containsKey(11));
|
||||
System.out.println(
|
||||
"map.containsKey(11): " + map.containsKey(11));
|
||||
System.out.println("map.get(11): " + map.get(11));
|
||||
System.out.println("map.containsValue(\"F0\"): "
|
||||
+ map.containsValue("F0"));
|
||||
|
@ -15,9 +15,11 @@ public class Utilities {
|
||||
Collections.singletonList("Four")));
|
||||
System.out.println("max: " + Collections.max(list));
|
||||
System.out.println("min: " + Collections.min(list));
|
||||
System.out.println("max w/ comparator: " + Collections.max(list,
|
||||
System.out.println(
|
||||
"max w/ comparator: " + Collections.max(list,
|
||||
String.CASE_INSENSITIVE_ORDER));
|
||||
System.out.println("min w/ comparator: " + Collections.min(list,
|
||||
System.out.println(
|
||||
"min w/ comparator: " + Collections.min(list,
|
||||
String.CASE_INSENSITIVE_ORDER));
|
||||
List<String> sublist =
|
||||
Arrays.asList("Four five six".split(" "));
|
||||
|
@ -8,31 +8,45 @@ public class CarWash {
|
||||
public enum Cycle {
|
||||
UNDERBODY {
|
||||
@Override
|
||||
void action() { System.out.println("Spraying the underbody"); }
|
||||
void action() {
|
||||
System.out.println("Spraying the underbody");
|
||||
}
|
||||
},
|
||||
WHEELWASH {
|
||||
@Override
|
||||
void action() { System.out.println("Washing the wheels"); }
|
||||
void action() {
|
||||
System.out.println("Washing the wheels");
|
||||
}
|
||||
},
|
||||
PREWASH {
|
||||
@Override
|
||||
void action() { System.out.println("Loosening the dirt"); }
|
||||
void action() {
|
||||
System.out.println("Loosening the dirt");
|
||||
}
|
||||
},
|
||||
BASIC {
|
||||
@Override
|
||||
void action() { System.out.println("The basic wash"); }
|
||||
void action() {
|
||||
System.out.println("The basic wash");
|
||||
}
|
||||
},
|
||||
HOTWAX {
|
||||
@Override
|
||||
void action() { System.out.println("Applying hot wax"); }
|
||||
void action() {
|
||||
System.out.println("Applying hot wax");
|
||||
}
|
||||
},
|
||||
RINSE {
|
||||
@Override
|
||||
void action() { System.out.println("Rinsing"); }
|
||||
void action() {
|
||||
System.out.println("Rinsing");
|
||||
}
|
||||
},
|
||||
BLOWDRY {
|
||||
@Override
|
||||
void action() { System.out.println("Blowing dry"); }
|
||||
void action() {
|
||||
System.out.println("Blowing dry");
|
||||
}
|
||||
};
|
||||
abstract void action();
|
||||
}
|
||||
|
@ -10,8 +10,10 @@ public class EnumClass {
|
||||
public static void main(String[] args) {
|
||||
for(Shrubbery s : Shrubbery.values()) {
|
||||
System.out.println(s + " ordinal: " + s.ordinal());
|
||||
System.out.print(s.compareTo(Shrubbery.CRAWLING) + " ");
|
||||
System.out.print(s.equals(Shrubbery.CRAWLING) + " ");
|
||||
System.out.print(
|
||||
s.compareTo(Shrubbery.CRAWLING) + " ");
|
||||
System.out.print(
|
||||
s.equals(Shrubbery.CRAWLING) + " ");
|
||||
System.out.println(s == Shrubbery.CRAWLING);
|
||||
System.out.println(s.getDeclaringClass());
|
||||
System.out.println(s.name());
|
||||
|
@ -13,9 +13,11 @@ public class EnumMaps {
|
||||
public static void main(String[] args) {
|
||||
EnumMap<AlarmPoints,Command> em =
|
||||
new EnumMap<>(AlarmPoints.class);
|
||||
em.put(KITCHEN, () -> System.out.println("Kitchen fire!"));
|
||||
em.put(BATHROOM, () -> System.out.println("Bathroom alert!"));
|
||||
for(Map.Entry<AlarmPoints,Command> e : em.entrySet()) {
|
||||
em.put(KITCHEN,
|
||||
() -> System.out.println("Kitchen fire!"));
|
||||
em.put(BATHROOM,
|
||||
() -> System.out.println("Bathroom alert!"));
|
||||
for(Map.Entry<AlarmPoints,Command> e : em.entrySet()){
|
||||
System.out.print(e.getKey() + ": ");
|
||||
e.getValue().action();
|
||||
}
|
||||
|
@ -19,7 +19,8 @@ public enum OzWitch {
|
||||
public String getDescription() { return description; }
|
||||
public static void main(String[] args) {
|
||||
for(OzWitch witch : OzWitch.values())
|
||||
System.out.println(witch + ": " + witch.getDescription());
|
||||
System.out.println(
|
||||
witch + ": " + witch.getDescription());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
|
@ -67,7 +67,8 @@ public class PostOffice {
|
||||
boolean handle(Mail m) {
|
||||
switch(m.generalDelivery) {
|
||||
case YES:
|
||||
System.out.println("Using general delivery for " + m);
|
||||
System.out.println(
|
||||
"Using general delivery for " + m);
|
||||
return true;
|
||||
default: return false;
|
||||
}
|
||||
@ -82,7 +83,8 @@ public class PostOffice {
|
||||
switch(m.address) {
|
||||
case INCORRECT: return false;
|
||||
default:
|
||||
System.out.println("Delivering "+ m + " automatically");
|
||||
System.out.println(
|
||||
"Delivering "+ m + " automatically");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -97,7 +99,8 @@ public class PostOffice {
|
||||
switch(m.address) {
|
||||
case INCORRECT: return false;
|
||||
default:
|
||||
System.out.println("Delivering " + m + " normally");
|
||||
System.out.println(
|
||||
"Delivering " + m + " normally");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@ -109,7 +112,8 @@ public class PostOffice {
|
||||
switch(m.returnAddress) {
|
||||
case MISSING: return false;
|
||||
default:
|
||||
System.out.println("Returning " + m + " to sender");
|
||||
System.out.println(
|
||||
"Returning " + m + " to sender");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -11,11 +11,13 @@ enum Explore { HERE, THERE }
|
||||
|
||||
public class Reflection {
|
||||
public static Set<String> analyze(Class<?> enumClass) {
|
||||
System.out.println("----- Analyzing " + enumClass + " -----");
|
||||
System.out.println(
|
||||
"----- Analyzing " + enumClass + " -----");
|
||||
System.out.println("Interfaces:");
|
||||
for(Type t : enumClass.getGenericInterfaces())
|
||||
System.out.println(t);
|
||||
System.out.println("Base: " + enumClass.getSuperclass());
|
||||
System.out.println(
|
||||
"Base: " + enumClass.getSuperclass());
|
||||
System.out.println("Methods: ");
|
||||
Set<String> methods = new TreeSet<>();
|
||||
for(Method m : enumClass.getMethods())
|
||||
|
@ -2,6 +2,8 @@
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.stream.*;
|
||||
|
||||
public enum SpaceShip {
|
||||
SCOUT, CARGO, TRANSPORT, CRUISER, BATTLESHIP, MOTHERSHIP;
|
||||
@Override
|
||||
@ -11,9 +13,7 @@ public enum SpaceShip {
|
||||
return id.charAt(0) + lower;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
for(SpaceShip s : values()) {
|
||||
System.out.println(s);
|
||||
}
|
||||
Stream.of(values()).forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
|
@ -5,7 +5,8 @@
|
||||
|
||||
public class MultipleReturns {
|
||||
public static void f(int i) {
|
||||
System.out.println("Initialization that requires cleanup");
|
||||
System.out.println(
|
||||
"Initialization that requires cleanup");
|
||||
try {
|
||||
System.out.println("Point 1");
|
||||
if(i == 1) return;
|
||||
|
@ -6,8 +6,16 @@
|
||||
public class Switch {
|
||||
private boolean state = false;
|
||||
public boolean read() { return state; }
|
||||
public void on() { state = true; System.out.println(this); }
|
||||
public void off() { state = false; System.out.println(this); }
|
||||
public void on() {
|
||||
state = true;
|
||||
System.out.println(this);
|
||||
}
|
||||
public void off() {
|
||||
state = false;
|
||||
System.out.println(this);
|
||||
}
|
||||
@Override
|
||||
public String toString() { return state ? "on" : "off"; }
|
||||
public String toString() {
|
||||
return state ? "on" : "off";
|
||||
}
|
||||
}
|
||||
|
60
files/AddAndSubtractPaths.java
Normal file
60
files/AddAndSubtractPaths.java
Normal file
@ -0,0 +1,60 @@
|
||||
// files/AddAndSubtractPaths.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.nio.file.*;
|
||||
|
||||
public class AddAndSubtractPaths {
|
||||
static Path base = Paths.get("..", "..", "..")
|
||||
.toAbsolutePath()
|
||||
.normalize();
|
||||
static void show(int id, Path result) {
|
||||
if(result.isAbsolute())
|
||||
System.out.println("(" + id + ")r " +
|
||||
base.relativize(result));
|
||||
else
|
||||
System.out.println("(" + id + ") " + result);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
System.out.println(System.getProperty("os.name"));
|
||||
System.out.println(base);
|
||||
Path p = Paths.get("AddAndSubtractPaths.java")
|
||||
.toAbsolutePath();
|
||||
show(1, p);
|
||||
Path convoluted = p.getParent().getParent()
|
||||
.resolve("strings")
|
||||
.resolve("..")
|
||||
.resolve(p.getParent().getFileName());
|
||||
show(2, convoluted);
|
||||
show(3, convoluted.normalize());
|
||||
|
||||
Path p2 = Paths.get("..", "..");
|
||||
show(4, p2);
|
||||
show(5, p2.normalize());
|
||||
show(6, p2.toAbsolutePath().normalize());
|
||||
|
||||
Path p3 = Paths.get(".").toAbsolutePath();
|
||||
Path p4 = p3.resolve(p2);
|
||||
show(7, p4);
|
||||
show(8, p4.normalize());
|
||||
|
||||
Path p5 = Paths.get("").toAbsolutePath();
|
||||
show(9, p5);
|
||||
show(10, p5.resolveSibling("strings"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Windows 10
|
||||
C:\Users\Bruce\Documents\Git
|
||||
(1)r on-
|
||||
java\ExtractedExamples\files\AddAndSubtractPaths.java
|
||||
(2)r on-java\ExtractedExamples\strings\..\files
|
||||
(3)r on-java\ExtractedExamples\files
|
||||
(4) ..\..
|
||||
(5) ..\..
|
||||
(6)r on-java
|
||||
(7)r on-java\ExtractedExamples\files\.\..\..
|
||||
(8)r on-java
|
||||
(9)r on-java\ExtractedExamples\files
|
||||
(10)r on-java\ExtractedExamples\strings
|
||||
*/
|
41
files/File_System.java
Normal file
41
files/File_System.java
Normal file
@ -0,0 +1,41 @@
|
||||
// files/File_System.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.nio.file.*;
|
||||
|
||||
public class File_System {
|
||||
static void show(String id, Object o) {
|
||||
System.out.println(id + ": " + o);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
System.out.println(System.getProperty("os.name"));
|
||||
FileSystem fsys = FileSystems.getDefault();
|
||||
for(FileStore fs : fsys.getFileStores())
|
||||
show("File Store", fs);
|
||||
for(Path rd : fsys.getRootDirectories())
|
||||
show("Root Directory", rd);
|
||||
show("Separator", fsys.getSeparator());
|
||||
show("UserPrincipalLookupService",
|
||||
fsys.getUserPrincipalLookupService());
|
||||
show("isOpen", fsys.isOpen());
|
||||
show("isReadOnly", fsys.isReadOnly());
|
||||
show("FileSystemProvider", fsys.provider());
|
||||
show("File Attribute Views",
|
||||
fsys.supportedFileAttributeViews());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Windows 10
|
||||
File Store: (C:)
|
||||
Root Directory: C:\
|
||||
Root Directory: D:\
|
||||
Separator: \
|
||||
UserPrincipalLookupService:
|
||||
sun.nio.fs.WindowsFileSystem$LookupService$1@106d69c
|
||||
isOpen: true
|
||||
isReadOnly: false
|
||||
FileSystemProvider:
|
||||
sun.nio.fs.WindowsFileSystemProvider@52e922
|
||||
File Attribute Views: [owner, dos, acl, basic, user]
|
||||
*/
|
48
files/PartsOfPaths.java
Normal file
48
files/PartsOfPaths.java
Normal file
@ -0,0 +1,48 @@
|
||||
// files/PartsOfPaths.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.nio.file.*;
|
||||
|
||||
public class PartsOfPaths {
|
||||
public static void main(String[] args) {
|
||||
System.out.println(System.getProperty("os.name"));
|
||||
Path p =
|
||||
Paths.get("PartsOfPaths.java").toAbsolutePath();
|
||||
for(int i = 0; i < p.getNameCount(); i++)
|
||||
System.out.println(p.getName(i));
|
||||
Path sub = p.subpath(3, p.getNameCount() - 2);
|
||||
System.out.println(sub);
|
||||
System.out.println("ends with '.java': " +
|
||||
p.endsWith(".java"));
|
||||
for(Path pp : p) {
|
||||
System.out.print(pp + ": ");
|
||||
System.out.print(p.startsWith(pp) + " : ");
|
||||
System.out.println(p.endsWith(pp));
|
||||
}
|
||||
System.out.println("Starts with " + p.getRoot() +
|
||||
" " + p.startsWith(p.getRoot()));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Windows 10
|
||||
Users
|
||||
Bruce
|
||||
Documents
|
||||
Git
|
||||
on-java
|
||||
ExtractedExamples
|
||||
files
|
||||
PartsOfPaths.java
|
||||
Git\on-java\ExtractedExamples
|
||||
ends with '.java': false
|
||||
Users: false : false
|
||||
Bruce: false : false
|
||||
Documents: false : false
|
||||
Git: false : false
|
||||
on-java: false : false
|
||||
ExtractedExamples: false : false
|
||||
files: false : false
|
||||
PartsOfPaths.java: false : true
|
||||
Starts with C:\ true
|
||||
*/
|
56
files/PathAnalysis.java
Normal file
56
files/PathAnalysis.java
Normal file
@ -0,0 +1,56 @@
|
||||
// files/PathAnalysis.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.nio.file.*;
|
||||
import java.io.IOException;
|
||||
|
||||
public class PathAnalysis {
|
||||
static void say(String id, Object result) {
|
||||
System.out.print(id + ": ");
|
||||
System.out.println(result);
|
||||
}
|
||||
public
|
||||
static void main(String[] args) throws IOException {
|
||||
System.out.println(System.getProperty("os.name"));
|
||||
Path p =
|
||||
Paths.get("PathAnalysis.java").toAbsolutePath();
|
||||
say("Exists", Files.exists(p));
|
||||
say("Directory", Files.isDirectory(p));
|
||||
say("Executable", Files.isExecutable(p));
|
||||
say("Readable", Files.isReadable(p));
|
||||
say("RegularFile", Files.isRegularFile(p));
|
||||
say("Writable", Files.isWritable(p));
|
||||
say("notExists", Files.notExists(p));
|
||||
say("Hidden", Files.isHidden(p));
|
||||
say("size", Files.size(p));
|
||||
say("FileStore", Files.getFileStore(p));
|
||||
say("LastModified: ", Files.getLastModifiedTime(p));
|
||||
say("Owner", Files.getOwner(p));
|
||||
say("ContentType", Files.probeContentType(p));
|
||||
say("SymbolicLink", Files.isSymbolicLink(p));
|
||||
if(Files.isSymbolicLink(p))
|
||||
say("SymbolicLink", Files.readSymbolicLink(p));
|
||||
if(FileSystems.getDefault()
|
||||
.supportedFileAttributeViews().contains("posix"))
|
||||
say("PosixFilePermissions",
|
||||
Files.getPosixFilePermissions(p));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Windows 10
|
||||
Exists: true
|
||||
Directory: false
|
||||
Executable: true
|
||||
Readable: true
|
||||
RegularFile: true
|
||||
Writable: true
|
||||
notExists: false
|
||||
Hidden: false
|
||||
size: 1618
|
||||
FileStore: (C:)
|
||||
LastModified: : 2015-12-02T16:49:49.113339Z
|
||||
Owner: GROOT\Bruce (User)
|
||||
ContentType: null
|
||||
SymbolicLink: false
|
||||
*/
|
102
files/PathInfo.java
Normal file
102
files/PathInfo.java
Normal file
@ -0,0 +1,102 @@
|
||||
// files/PathInfo.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.nio.file.*;
|
||||
import java.net.URI;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
|
||||
public class PathInfo {
|
||||
static void show(String id, Object p) {
|
||||
System.out.println(id + ": " + p);
|
||||
}
|
||||
static void info(Path p) {
|
||||
show("toString", p);
|
||||
show("Exists", Files.exists(p));
|
||||
show("RegularFile", Files.isRegularFile(p));
|
||||
show("Directory", Files.isDirectory(p));
|
||||
show("Absolute", p.isAbsolute());
|
||||
show("FileName", p.getFileName());
|
||||
show("Parent", p.getParent());
|
||||
show("Root", p.getRoot());
|
||||
System.out.println("----------------");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
System.out.println(System.getProperty("os.name"));
|
||||
info(Paths.get(
|
||||
"C:", "path", "to", "nowhere", "NoFile.txt"));
|
||||
Path p = Paths.get("PathInfo.java");
|
||||
info(p);
|
||||
Path ap = p.toAbsolutePath();
|
||||
info(ap);
|
||||
info(ap.getParent());
|
||||
try {
|
||||
info(p.toRealPath());
|
||||
} catch (IOException e) {
|
||||
System.out.println(e);
|
||||
}
|
||||
URI u = p.toUri();
|
||||
System.out.println("URI: " + u);
|
||||
Path puri = Paths.get(u);
|
||||
System.out.println(Files.exists(puri));
|
||||
File f = ap.toFile(); // Don't be fooled
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Windows 10
|
||||
toString: C:\path\to\nowhere\NoFile.txt
|
||||
Exists: false
|
||||
RegularFile: false
|
||||
Directory: false
|
||||
Absolute: true
|
||||
FileName: NoFile.txt
|
||||
Parent: C:\path\to\nowhere
|
||||
Root: C:\
|
||||
----------------
|
||||
toString: PathInfo.java
|
||||
Exists: true
|
||||
RegularFile: true
|
||||
Directory: false
|
||||
Absolute: false
|
||||
FileName: PathInfo.java
|
||||
Parent: null
|
||||
Root: null
|
||||
----------------
|
||||
toString: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples\files\PathInfo.java
|
||||
Exists: true
|
||||
RegularFile: true
|
||||
Directory: false
|
||||
Absolute: true
|
||||
FileName: PathInfo.java
|
||||
Parent: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples\files
|
||||
Root: C:\
|
||||
----------------
|
||||
toString: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples\files
|
||||
Exists: true
|
||||
RegularFile: false
|
||||
Directory: true
|
||||
Absolute: true
|
||||
FileName: files
|
||||
Parent: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples
|
||||
Root: C:\
|
||||
----------------
|
||||
toString: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples\files\PathInfo.java
|
||||
Exists: true
|
||||
RegularFile: true
|
||||
Directory: false
|
||||
Absolute: true
|
||||
FileName: PathInfo.java
|
||||
Parent: C:\Users\Bruce\Documents\Git\on-
|
||||
java\ExtractedExamples\files
|
||||
Root: C:\
|
||||
----------------
|
||||
URI: file:///C:/Users/Bruce/Documents/Git/on-
|
||||
java/ExtractedExamples/files/PathInfo.java
|
||||
true
|
||||
*/
|
@ -7,11 +7,16 @@
|
||||
<import file="../Ant-Clean.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<jrun cls="AddAndSubtractPaths" />
|
||||
<jrun cls="DirectoryDemo" />
|
||||
<jrun cls="DirList" arguments='"D.*\.java"' />
|
||||
<jrun cls="DirList2" arguments='"D.*\.java"' />
|
||||
<jrun cls="DirList3" arguments='"D.*\.java"' />
|
||||
<jrun cls="File_System" />
|
||||
<jrun cls="MakeDirectories" arguments="MakeDirectoriesTest" />
|
||||
<jrun cls="PartsOfPaths" />
|
||||
<jrun cls="PathAnalysis" />
|
||||
<jrun cls="PathInfo" />
|
||||
</target>
|
||||
|
||||
</project>
|
||||
|
17
functional/AnonymousClosure.java
Normal file
17
functional/AnonymousClosure.java
Normal file
@ -0,0 +1,17 @@
|
||||
// functional/AnonymousClosure.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class AnonymousClosure {
|
||||
IntSupplier make_fun(int x) {
|
||||
int i = 0;
|
||||
// Same rules apply:
|
||||
// i++; // Not "effectively final"
|
||||
// x++; // Ditto
|
||||
return new IntSupplier() {
|
||||
public int getAsInt() { return x + i; }
|
||||
};
|
||||
}
|
||||
}
|
24
functional/BiConsumerPermutations.java
Normal file
24
functional/BiConsumerPermutations.java
Normal file
@ -0,0 +1,24 @@
|
||||
// functional/BiConsumerPermutations.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class BiConsumerPermutations {
|
||||
static BiConsumer<Integer, Double> bicid = (i, d) ->
|
||||
System.out.format("%d, %f\n", i, d);
|
||||
static BiConsumer<Double, Integer> bicdi = (d, i) ->
|
||||
System.out.format("%d, %f\n", i, d);
|
||||
static BiConsumer<Integer, Long> bicil = (i, l) ->
|
||||
System.out.format("%d, %d\n", i, l);
|
||||
public static void main(String[] args) {
|
||||
bicid.accept(47, 11.34);
|
||||
bicdi.accept(22.45, 92);
|
||||
bicil.accept(1, 11L);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
47, 11.340000
|
||||
92, 22.450000
|
||||
1, 11
|
||||
*/
|
45
functional/ClassFunctionals.java
Normal file
45
functional/ClassFunctionals.java
Normal file
@ -0,0 +1,45 @@
|
||||
// functional/ClassFunctionals.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
class AA {}
|
||||
class BB {}
|
||||
class CC {}
|
||||
|
||||
public class ClassFunctionals {
|
||||
static AA f1() { return new AA(); }
|
||||
static int f2(AA aa1, AA aa2) { return 1; }
|
||||
static void f3(AA aa) {}
|
||||
static void f4(AA aa, BB bb) {}
|
||||
static CC f5(AA aa) { return new CC(); }
|
||||
static CC f6(AA aa, BB bb) { return new CC(); }
|
||||
static boolean f7(AA aa) { return true; }
|
||||
static boolean f8(AA aa, BB bb) { return true; }
|
||||
static AA f9(AA aa) { return new AA(); }
|
||||
static AA f10(AA aa1, AA aa2) { return new AA(); }
|
||||
public static void main(String[] args) {
|
||||
Supplier<AA> s = ClassFunctionals::f1;
|
||||
s.get();
|
||||
Comparator<AA> c = ClassFunctionals::f2;
|
||||
c.compare(new AA(), new AA());
|
||||
Consumer<AA> cons = ClassFunctionals::f3;
|
||||
cons.accept(new AA());
|
||||
BiConsumer<AA,BB> bicons = ClassFunctionals::f4;
|
||||
bicons.accept(new AA(), new BB());
|
||||
Function<AA,CC> f = ClassFunctionals::f5;
|
||||
CC cc = f.apply(new AA());
|
||||
BiFunction<AA,BB,CC> bif = ClassFunctionals::f6;
|
||||
cc = bif.apply(new AA(), new BB());
|
||||
Predicate<AA> p = ClassFunctionals::f7;
|
||||
boolean result = p.test(new AA());
|
||||
BiPredicate<AA,BB> bip = ClassFunctionals::f8;
|
||||
result = bip.test(new AA(), new BB());
|
||||
UnaryOperator<AA> uo = ClassFunctionals::f9;
|
||||
AA aa = uo.apply(new AA());
|
||||
BinaryOperator<AA> bo = ClassFunctionals::f10;
|
||||
aa = bo.apply(new AA(), new AA());
|
||||
}
|
||||
}
|
12
functional/Closure1.java
Normal file
12
functional/Closure1.java
Normal file
@ -0,0 +1,12 @@
|
||||
// functional/Closure1.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure1 {
|
||||
int i;
|
||||
IntSupplier make_fun(int x) {
|
||||
return () -> x + i++;
|
||||
}
|
||||
}
|
12
functional/Closure2.java
Normal file
12
functional/Closure2.java
Normal file
@ -0,0 +1,12 @@
|
||||
// functional/Closure2.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure2 {
|
||||
IntSupplier make_fun(int x) {
|
||||
int i = 0;
|
||||
return () -> x + i;
|
||||
}
|
||||
}
|
14
functional/Closure3.java
Normal file
14
functional/Closure3.java
Normal file
@ -0,0 +1,14 @@
|
||||
// functional/Closure3.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// {CompileTimeError} (Won't compile)
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure3 {
|
||||
IntSupplier make_fun(int x) {
|
||||
int i = 0;
|
||||
// Neither x++ nor i++ will work:
|
||||
return () -> x++ + i++;
|
||||
}
|
||||
}
|
12
functional/Closure4.java
Normal file
12
functional/Closure4.java
Normal file
@ -0,0 +1,12 @@
|
||||
// functional/Closure4.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure4 {
|
||||
IntSupplier make_fun(final int x) {
|
||||
final int i = 0;
|
||||
return () -> x + i;
|
||||
}
|
||||
}
|
15
functional/Closure5.java
Normal file
15
functional/Closure5.java
Normal file
@ -0,0 +1,15 @@
|
||||
// functional/Closure5.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// {CompileTimeError} (Won't compile)
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure5 {
|
||||
IntSupplier make_fun(int x) {
|
||||
int i = 0;
|
||||
i++;
|
||||
x++;
|
||||
return () -> x + i;
|
||||
}
|
||||
}
|
16
functional/Closure6.java
Normal file
16
functional/Closure6.java
Normal file
@ -0,0 +1,16 @@
|
||||
// functional/Closure6.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure6 {
|
||||
IntSupplier make_fun(int x) {
|
||||
int i = 0;
|
||||
i++;
|
||||
x++;
|
||||
final int i_final = i;
|
||||
final int x_final = x;
|
||||
return () -> x_final + i_final;
|
||||
}
|
||||
}
|
14
functional/Closure7.java
Normal file
14
functional/Closure7.java
Normal file
@ -0,0 +1,14 @@
|
||||
// functional/Closure7.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// {CompileTimeError} (Won't compile)
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure7 {
|
||||
IntSupplier make_fun(int x) {
|
||||
Integer i = new Integer(0);
|
||||
i = i + 1;
|
||||
return () -> x + i;
|
||||
}
|
||||
}
|
32
functional/Closure8.java
Normal file
32
functional/Closure8.java
Normal file
@ -0,0 +1,32 @@
|
||||
// functional/Closure8.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure8 {
|
||||
Supplier<List<Integer>> make_fun() {
|
||||
final List<Integer> ai = new ArrayList<>();
|
||||
ai.add(1);
|
||||
return () -> ai;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Closure8 c7 = new Closure8();
|
||||
List<Integer>
|
||||
l1 = c7.make_fun().get(),
|
||||
l2 = c7.make_fun().get();
|
||||
System.out.println(l1);
|
||||
System.out.println(l2);
|
||||
l1.add(42);
|
||||
l2.add(96);
|
||||
System.out.println(l1);
|
||||
System.out.println(l2);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
[1]
|
||||
[1]
|
||||
[1, 42]
|
||||
[1, 96]
|
||||
*/
|
15
functional/Closure9.java
Normal file
15
functional/Closure9.java
Normal file
@ -0,0 +1,15 @@
|
||||
// functional/Closure9.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// {CompileTimeError} (Won't compile)
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
public class Closure9 {
|
||||
Supplier<List<Integer>> make_fun() {
|
||||
List<Integer> ai = new ArrayList<>();
|
||||
ai = new ArrayList<>(); // Reassignment
|
||||
return () -> ai;
|
||||
}
|
||||
}
|
17
functional/ConsumeFunction.java
Normal file
17
functional/ConsumeFunction.java
Normal file
@ -0,0 +1,17 @@
|
||||
// functional/ConsumeFunction.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
class One {}
|
||||
class Two {}
|
||||
|
||||
public class ConsumeFunction {
|
||||
static Two consume(Function<One,Two> onetwo) {
|
||||
return onetwo.apply(new One());
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Two two = consume(one -> new Two());
|
||||
}
|
||||
}
|
@ -2,35 +2,35 @@
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Demonstrates java.util.function
|
||||
import java.util.function.*;
|
||||
|
||||
class Dog {
|
||||
String name;
|
||||
int age = -1; // For "unknown"
|
||||
Dog() { name = "stray"; }
|
||||
Dog(String nm) { name = nm; }
|
||||
Dog(String nm, int yrs) { name = nm; age = yrs; }
|
||||
}
|
||||
|
||||
interface MakeNoArgs {
|
||||
Dog make();
|
||||
}
|
||||
|
||||
interface Make1Arg {
|
||||
Dog make(String nm);
|
||||
}
|
||||
|
||||
interface Make2Args {
|
||||
Dog make(String nm, int age);
|
||||
}
|
||||
|
||||
public class CtorReference {
|
||||
public CtorReference() {
|
||||
System.out.println("Inside CtorReference()");
|
||||
}
|
||||
public CtorReference(int i) {
|
||||
System.out.println("Inside CtorReference(i)");
|
||||
}
|
||||
public CtorReference(int i, double d) {
|
||||
System.out.println("Inside CtorReference(i, d)");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Supplier<CtorReference> cr0 =
|
||||
CtorReference::new;
|
||||
CtorReference r0 = cr0.get();
|
||||
MakeNoArgs mna = Dog::new; // (1)
|
||||
Make1Arg m1a = Dog::new; // (2)
|
||||
Make2Args m2a = Dog::new; // (3)
|
||||
|
||||
Function<Integer, CtorReference> cr1 =
|
||||
CtorReference::new;
|
||||
CtorReference r1 = cr1.apply(1);
|
||||
|
||||
BiFunction<Integer, Double, CtorReference> cr2 =
|
||||
CtorReference::new;
|
||||
CtorReference r2 = cr2.apply(1, 2.0);
|
||||
Dog dn = mna.make();
|
||||
Dog d1 = m1a.make("Comet");
|
||||
Dog d2 = m2a.make("Ralph", 4);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Inside CtorReference()
|
||||
Inside CtorReference(i)
|
||||
Inside CtorReference(i, d)
|
||||
*/
|
||||
|
17
functional/CurriedIntAdd.java
Normal file
17
functional/CurriedIntAdd.java
Normal file
@ -0,0 +1,17 @@
|
||||
// functional/CurriedIntAdd.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class CurriedIntAdd {
|
||||
public static void main(String[] args) {
|
||||
IntFunction<IntUnaryOperator>
|
||||
curriedIntAdd = a -> b -> a + b;
|
||||
IntUnaryOperator add4 = curriedIntAdd.apply(4);
|
||||
System.out.println(add4.applyAsInt(5));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
9
|
||||
*/
|
23
functional/Curry3Args.java
Normal file
23
functional/Curry3Args.java
Normal file
@ -0,0 +1,23 @@
|
||||
// functional/Curry3Args.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class Curry3Args {
|
||||
public static void main(String[] args) {
|
||||
Function<String,
|
||||
Function<String,
|
||||
Function<String, String>>> sum =
|
||||
a -> b -> c -> a + b + c;
|
||||
Function<String,
|
||||
Function<String, String>> hi =
|
||||
sum.apply("Hi ");
|
||||
Function<String, String> ho =
|
||||
hi.apply("Ho ");
|
||||
System.out.println(ho.apply("Hup"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Hi Ho Hup
|
||||
*/
|
@ -1,25 +0,0 @@
|
||||
// functional/CurryingAndPartialFunctionApplication.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class CurryingAndPartialFunctionApplication
|
||||
{
|
||||
public static void main(String[] args)
|
||||
{
|
||||
IntBinaryOperator simpleAdd = (a, b) -> a + b;
|
||||
IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;
|
||||
|
||||
// Demonstrating simple add:
|
||||
System.out.println(simpleAdd.applyAsInt(4, 5));
|
||||
|
||||
// Demonstrating curried add:
|
||||
System.out.println(curriedAdd.apply(4).applyAsInt(5));
|
||||
|
||||
// Curried version lets you perform partial application:
|
||||
IntUnaryOperator adder5 = curriedAdd.apply(5);
|
||||
System.out.println(adder5.applyAsInt(4));
|
||||
System.out.println(adder5.applyAsInt(6));
|
||||
}
|
||||
}
|
34
functional/CurryingAndPartials.java
Normal file
34
functional/CurryingAndPartials.java
Normal file
@ -0,0 +1,34 @@
|
||||
// functional/CurryingAndPartials.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class CurryingAndPartials {
|
||||
// Uncurried:
|
||||
static String uncurried(String a, String b) {
|
||||
return a + b;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// Curried function:
|
||||
Function<String, Function<String, String>> sum =
|
||||
a -> b -> a + b; // (1)
|
||||
|
||||
System.out.println(uncurried("Hi ", "Ho"));
|
||||
|
||||
Function<String, String>
|
||||
hi = sum.apply("Hi "); // (2)
|
||||
System.out.println(hi.apply("Ho"));
|
||||
|
||||
// Partial application:
|
||||
Function<String, String> sumHi = sum.apply("Hup ");
|
||||
System.out.println(sumHi.apply("Ho"));
|
||||
System.out.println(sumHi.apply("Hey"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Hi Ho
|
||||
Hi Ho
|
||||
Hup Ho
|
||||
Hup Hey
|
||||
*/
|
@ -1,65 +0,0 @@
|
||||
// functional/Factories.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
interface Service {
|
||||
void method1();
|
||||
void method2();
|
||||
}
|
||||
|
||||
interface ServiceFactory {
|
||||
Service getService();
|
||||
}
|
||||
|
||||
class Implementation1 implements Service {
|
||||
private Implementation1() {}
|
||||
public void method1() { System.out.println("Implementation1 method1");}
|
||||
public void method2() { System.out.println("Implementation1 method2");}
|
||||
public static ServiceFactory factory =
|
||||
new ServiceFactory() {
|
||||
public Service getService() {
|
||||
return new Implementation1();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
class Implementation2 implements Service {
|
||||
private Implementation2() {}
|
||||
public void method1() { System.out.println("Implementation2 method1");}
|
||||
public void method2() { System.out.println("Implementation2 method2");}
|
||||
// Use method reference instead:
|
||||
public static ServiceFactory factory =
|
||||
Implementation2::new; // Constructor reference
|
||||
}
|
||||
|
||||
class Implementation3 implements Service {
|
||||
private Implementation3() {}
|
||||
public void method1() { System.out.println("Implementation3 method1");}
|
||||
public void method2() { System.out.println("Implementation3 method2");}
|
||||
// Use lambda expression instead:
|
||||
public static ServiceFactory factory =
|
||||
() -> new Implementation3();
|
||||
}
|
||||
|
||||
public class Factories {
|
||||
public static void serviceConsumer(ServiceFactory fact) {
|
||||
Service s = fact.getService();
|
||||
s.method1();
|
||||
s.method2();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
serviceConsumer(Implementation1.factory);
|
||||
// Implementations are completely interchangeable:
|
||||
serviceConsumer(Implementation2.factory);
|
||||
serviceConsumer(Implementation3.factory);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Implementation1 method1
|
||||
Implementation1 method2
|
||||
Implementation2 method1
|
||||
Implementation2 method2
|
||||
Implementation3 method1
|
||||
Implementation3 method2
|
||||
*/
|
24
functional/FunctionComposition.java
Normal file
24
functional/FunctionComposition.java
Normal file
@ -0,0 +1,24 @@
|
||||
// functional/FunctionComposition.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class FunctionComposition {
|
||||
static Function<String, String>
|
||||
f1 = s -> {
|
||||
System.out.println(s);
|
||||
return s.replace('A', '_');
|
||||
},
|
||||
f2 = s -> s.substring(3),
|
||||
f3 = s -> s.toLowerCase(),
|
||||
f4 = f1.compose(f2).andThen(f3);
|
||||
public static void main(String[] args) {
|
||||
System.out.println(
|
||||
f4.apply("GO AFTER ALL AMBULANCES"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
AFTER ALL AMBULANCES
|
||||
_fter _ll _mbul_nces
|
||||
*/
|
65
functional/FunctionVariants.java
Normal file
65
functional/FunctionVariants.java
Normal file
@ -0,0 +1,65 @@
|
||||
// functional/FunctionVariants.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
class Foo {}
|
||||
|
||||
class Bar {
|
||||
Foo f;
|
||||
public Bar(Foo f) { this.f = f; }
|
||||
}
|
||||
|
||||
class IBaz {
|
||||
int i;
|
||||
public IBaz(int i) {
|
||||
this.i = i;
|
||||
}
|
||||
}
|
||||
|
||||
class LBaz {
|
||||
long l;
|
||||
public LBaz(long l) {
|
||||
this.l = l;
|
||||
}
|
||||
}
|
||||
|
||||
class DBaz {
|
||||
double d;
|
||||
public DBaz(double d) {
|
||||
this.d = d;
|
||||
}
|
||||
}
|
||||
|
||||
public class FunctionVariants {
|
||||
static Function<Foo,Bar> f1 = f -> new Bar(f);
|
||||
static IntFunction<IBaz> f2 = i -> new IBaz(i);
|
||||
static LongFunction<LBaz> f3 = l -> new LBaz(l);
|
||||
static DoubleFunction<DBaz> f4 = d -> new DBaz(d);
|
||||
static ToIntFunction<IBaz> f5 = ib -> ib.i;
|
||||
static ToLongFunction<LBaz> f6 = lb -> lb.l;
|
||||
static ToDoubleFunction<DBaz> f7 = db -> db.d;
|
||||
static IntToLongFunction f8 = i -> i;
|
||||
static IntToDoubleFunction f9 = i -> i;
|
||||
static LongToIntFunction f10 = l -> (int)l;
|
||||
static LongToDoubleFunction f11 = l -> l;
|
||||
static DoubleToIntFunction f12 = d -> (int)d;
|
||||
static DoubleToLongFunction f13 = d -> (long)d;
|
||||
|
||||
public static void main(String[] args) {
|
||||
Bar b = f1.apply(new Foo());
|
||||
IBaz ib = f2.apply(11);
|
||||
LBaz lb = f3.apply(11);
|
||||
DBaz db = f4.apply(11);
|
||||
int i = f5.applyAsInt(ib);
|
||||
long l = f6.applyAsLong(lb);
|
||||
double d = f7.applyAsDouble(db);
|
||||
l = f8.applyAsLong(12);
|
||||
d = f9.applyAsDouble(12);
|
||||
i = f10.applyAsInt(12);
|
||||
d = f11.applyAsDouble(12);
|
||||
i = f12.applyAsInt(13.0);
|
||||
l = f13.applyAsLong(13.0);
|
||||
}
|
||||
}
|
12
functional/FunctionWithWrapped.java
Normal file
12
functional/FunctionWithWrapped.java
Normal file
@ -0,0 +1,12 @@
|
||||
// functional/FunctionWithWrapped.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class FunctionWithWrapped {
|
||||
public static void main(String[] args) {
|
||||
Function<Integer, Double> fid = i -> (double)i;
|
||||
IntToDoubleFunction fid2 = i -> i;
|
||||
}
|
||||
}
|
39
functional/FunctionalAnnotation.java
Normal file
39
functional/FunctionalAnnotation.java
Normal file
@ -0,0 +1,39 @@
|
||||
// functional/FunctionalAnnotation.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
@FunctionalInterface
|
||||
interface Functional {
|
||||
String goodbye(String arg);
|
||||
}
|
||||
|
||||
interface FunctionalNoAnn {
|
||||
String goodbye(String arg);
|
||||
}
|
||||
|
||||
/*
|
||||
@FunctionalInterface
|
||||
interface NotFunctional {
|
||||
String goodbye(String arg);
|
||||
String hello(String arg);
|
||||
}
|
||||
Produces error message:
|
||||
NotFunctional is not a functional interface
|
||||
multiple non-overriding abstract methods
|
||||
found in interface NotFunctional
|
||||
*/
|
||||
|
||||
public class FunctionalAnnotation {
|
||||
public String goodbye(String arg) {
|
||||
return "Goodbye, " + arg;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
FunctionalAnnotation fa = new FunctionalAnnotation();
|
||||
Functional f = fa::goodbye;
|
||||
FunctionalNoAnn fna = fa::goodbye;
|
||||
// Functional fac = fa; // Incompatible
|
||||
Functional fl = a -> "Goodbye, " + a;
|
||||
FunctionalNoAnn fnal = a -> "Goodbye, " + a;
|
||||
}
|
||||
}
|
@ -1,72 +0,0 @@
|
||||
// functional/Games.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Using anonymous inner classes with the Game framework.
|
||||
|
||||
interface Game { boolean move(); }
|
||||
interface GameFactory { Game getGame(); }
|
||||
|
||||
class Checkers implements Game {
|
||||
private Checkers() {}
|
||||
private int moves = 0;
|
||||
private static final int MOVES = 3;
|
||||
@Override
|
||||
public boolean move() {
|
||||
System.out.println("Checkers move " + moves);
|
||||
return ++moves != MOVES;
|
||||
}
|
||||
public static GameFactory factory = new GameFactory() {
|
||||
public Game getGame() { return new Checkers(); }
|
||||
};
|
||||
}
|
||||
|
||||
class Chess implements Game {
|
||||
private Chess() {}
|
||||
private int moves = 0;
|
||||
private static final int MOVES = 4;
|
||||
public boolean move() {
|
||||
System.out.println("Chess move " + moves);
|
||||
return ++moves != MOVES;
|
||||
}
|
||||
// Use a lambda expression instead:
|
||||
public static GameFactory factory = () -> new Chess();
|
||||
}
|
||||
|
||||
class TicTacToe implements Game {
|
||||
private TicTacToe() {}
|
||||
private int moves = 0;
|
||||
private static final int MOVES = 4;
|
||||
public boolean move() {
|
||||
System.out.println("TicTacToe move " + moves);
|
||||
return ++moves != MOVES;
|
||||
}
|
||||
// Use a method reference instead:
|
||||
public static GameFactory factory = TicTacToe::new;
|
||||
}
|
||||
|
||||
public class Games {
|
||||
public static void playGame(GameFactory factory) {
|
||||
Game s = factory.getGame();
|
||||
while(s.move())
|
||||
;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
playGame(Checkers.factory);
|
||||
playGame(Chess.factory);
|
||||
playGame(TicTacToe.factory);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Checkers move 0
|
||||
Checkers move 1
|
||||
Checkers move 2
|
||||
Chess move 0
|
||||
Chess move 1
|
||||
Chess move 2
|
||||
Chess move 3
|
||||
TicTacToe move 0
|
||||
TicTacToe move 1
|
||||
TicTacToe move 2
|
||||
TicTacToe move 3
|
||||
*/
|
8
functional/IntCall.java
Normal file
8
functional/IntCall.java
Normal file
@ -0,0 +1,8 @@
|
||||
// functional/IntCall.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
interface IntCall {
|
||||
int call(int arg);
|
||||
}
|
@ -16,35 +16,33 @@ interface Multi {
|
||||
}
|
||||
|
||||
public class LambdaExpressions {
|
||||
Description desc = new Description() {
|
||||
@Override
|
||||
public String brief() {
|
||||
return "Short info";
|
||||
}
|
||||
|
||||
static Body bod = h -> h + " No Parens!"; // (1)
|
||||
|
||||
static Body bod2 = (h) -> h + " More details"; // (2)
|
||||
|
||||
static Description desc = () -> "Short info"; // (3)
|
||||
|
||||
static Multi mult = (h, n) -> h + n; // (4)
|
||||
|
||||
static Description moreLines = () -> { // (5)
|
||||
System.out.println("moreLines()");
|
||||
return "from moreLines()";
|
||||
};
|
||||
Description desc2 = () -> "Short info";
|
||||
|
||||
Body bod = (h) -> h + " More details";
|
||||
Body bod2 = h -> h + " No Parens!";
|
||||
|
||||
Multi mult = (h, n) -> h + n;
|
||||
// Parens are required with multiple args:
|
||||
// Multi mult2 = h, n -> h + n; // Nope
|
||||
|
||||
public static void main(String[] args) {
|
||||
LambdaExpressions le =
|
||||
new LambdaExpressions();
|
||||
System.out.println(le.desc.brief());
|
||||
System.out.println(le.desc2.brief());
|
||||
System.out.println(le.bod.detailed("Hi!"));
|
||||
System.out.println(le.bod2.detailed("Oh!"));
|
||||
System.out.println(le.mult.twoArg("Pi! ", 3.14159));
|
||||
System.out.println(bod.detailed("Oh!"));
|
||||
System.out.println(bod2.detailed("Hi!"));
|
||||
System.out.println(desc.brief());
|
||||
System.out.println(mult.twoArg("Pi! ", 3.14159));
|
||||
System.out.println(moreLines.brief());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Short info
|
||||
Short info
|
||||
Hi! More details
|
||||
Oh! No Parens!
|
||||
Hi! More details
|
||||
Short info
|
||||
Pi! 3.14159
|
||||
moreLines()
|
||||
from moreLines()
|
||||
*/
|
||||
|
31
functional/MethodConversion.java
Normal file
31
functional/MethodConversion.java
Normal file
@ -0,0 +1,31 @@
|
||||
// functional/MethodConversion.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
class In1 {}
|
||||
class In2 {}
|
||||
|
||||
public class MethodConversion {
|
||||
static void accept(In1 i1, In2 i2) {
|
||||
System.out.println("accept()");
|
||||
}
|
||||
static void someOtherName(In1 i1, In2 i2) {
|
||||
System.out.println("someOtherName()");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
BiConsumer<In1,In2> bic;
|
||||
|
||||
bic = MethodConversion::accept;
|
||||
bic.accept(new In1(), new In2());
|
||||
|
||||
bic = MethodConversion::someOtherName;
|
||||
// bic.someOtherName(new In1(), new In2()); // Nope
|
||||
bic.accept(new In1(), new In2());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
accept()
|
||||
someOtherName()
|
||||
*/
|
@ -4,34 +4,50 @@
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.*;
|
||||
|
||||
interface Callable { // (1)
|
||||
void call(String s);
|
||||
}
|
||||
|
||||
class Describe {
|
||||
void show(String msg) { // (2)
|
||||
System.out.println(msg);
|
||||
}
|
||||
}
|
||||
|
||||
public class MethodReferences {
|
||||
static void hello(String name) { // (3)
|
||||
System.out.println("Hello, " + name);
|
||||
}
|
||||
static class Description {
|
||||
String describe;
|
||||
public Description(String desc) {
|
||||
describe = desc;
|
||||
String about;
|
||||
public Description(String desc) { about = desc; }
|
||||
void help(String msg) { // (4)
|
||||
System.out.println(about + " " + msg);
|
||||
}
|
||||
}
|
||||
static class Helper {
|
||||
static void assist(String msg) { // (5)
|
||||
System.out.println(msg);
|
||||
}
|
||||
public void show() { System.out.println(describe); }
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
List<String> keys = Arrays.asList(
|
||||
"Every", "Good", "Boy", "Deserves", "Fudge");
|
||||
keys.forEach(System.out::println); // (1)
|
||||
Describe d = new Describe();
|
||||
Callable c = d::show; // (6)
|
||||
c.call("call()"); // (7)
|
||||
|
||||
List<Description> descriptions = new ArrayList<>();
|
||||
for(String k : keys)
|
||||
descriptions.add(new Description(k));
|
||||
descriptions.forEach(Description::show); // (2)
|
||||
c = MethodReferences::hello; // (8)
|
||||
c.call("Bob");
|
||||
|
||||
c = new Description("valuable")::help; // (9)
|
||||
c.call("information");
|
||||
|
||||
c = Helper::assist; // (10)
|
||||
c.call("Help!");
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Every
|
||||
Good
|
||||
Boy
|
||||
Deserves
|
||||
Fudge
|
||||
Every
|
||||
Good
|
||||
Boy
|
||||
Deserves
|
||||
Fudge
|
||||
call()
|
||||
Hello, Bob
|
||||
valuable information
|
||||
Help!
|
||||
*/
|
||||
|
36
functional/MultiUnbound.java
Normal file
36
functional/MultiUnbound.java
Normal file
@ -0,0 +1,36 @@
|
||||
// functional/MultiUnbound.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Unbound methods with multiple arguments
|
||||
|
||||
class This {
|
||||
void two(int i, double d) {}
|
||||
void three(int i, double d, String s) {}
|
||||
void four(int i, double d, String s, char c) {}
|
||||
}
|
||||
|
||||
interface TwoArgs {
|
||||
void call2(This _this, int i, double d);
|
||||
}
|
||||
|
||||
interface ThreeArgs {
|
||||
void call3(This _this, int i, double d, String s);
|
||||
}
|
||||
|
||||
interface FourArgs {
|
||||
void call4(
|
||||
This _this, int i, double d, String s, char c);
|
||||
}
|
||||
|
||||
public class MultiUnbound {
|
||||
public static void main(String[] args) {
|
||||
TwoArgs twoargs = This::two;
|
||||
ThreeArgs threeargs = This::three;
|
||||
FourArgs fourargs = This::four;
|
||||
This _this = new This();
|
||||
twoargs.call2(_this, 11, 3.14);
|
||||
threeargs.call3(_this, 11, 3.14, "Three");
|
||||
fourargs.call4(_this, 11, 3.14, "Four", 'Z');
|
||||
}
|
||||
}
|
23
functional/PredicateComposition.java
Normal file
23
functional/PredicateComposition.java
Normal file
@ -0,0 +1,23 @@
|
||||
// functional/PredicateComposition.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
import java.util.stream.*;
|
||||
|
||||
public class PredicateComposition {
|
||||
static Predicate<String>
|
||||
p1 = s -> s.contains("bar"),
|
||||
p2 = s -> s.length() < 5,
|
||||
p3 = s -> s.contains("foo"),
|
||||
p4 = p1.negate().and(p2).or(p3);
|
||||
public static void main(String[] args) {
|
||||
Stream.of("bar", "foobar", "foobaz", "fongopuckey")
|
||||
.filter(p4)
|
||||
.forEach(System.out::println);
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
foobar
|
||||
foobaz
|
||||
*/
|
21
functional/ProduceFunction.java
Normal file
21
functional/ProduceFunction.java
Normal file
@ -0,0 +1,21 @@
|
||||
// functional/ProduceFunction.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
interface
|
||||
FuncSS extends Function<String, String> {} // (1)
|
||||
|
||||
public class ProduceFunction {
|
||||
static FuncSS produce() {
|
||||
return s -> s.toLowerCase(); // (2)
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
FuncSS f = produce();
|
||||
System.out.println(f.apply("YELLING"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
yelling
|
||||
*/
|
26
functional/RecursiveFactorial.java
Normal file
26
functional/RecursiveFactorial.java
Normal file
@ -0,0 +1,26 @@
|
||||
// functional/RecursiveFactorial.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
public class RecursiveFactorial {
|
||||
static IntCall fact;
|
||||
public static void main(String[] args) {
|
||||
fact = n -> n == 0 ? 1 : n * fact.call(n - 1);
|
||||
for(int i = 0; i <= 10; i++)
|
||||
System.out.println(fact.call(i));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
1
|
||||
1
|
||||
2
|
||||
6
|
||||
24
|
||||
120
|
||||
720
|
||||
5040
|
||||
40320
|
||||
362880
|
||||
3628800
|
||||
*/
|
32
functional/RecursiveFibonacci.java
Normal file
32
functional/RecursiveFibonacci.java
Normal file
@ -0,0 +1,32 @@
|
||||
// functional/RecursiveFibonacci.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
public class RecursiveFibonacci {
|
||||
IntCall fib;
|
||||
RecursiveFibonacci() {
|
||||
fib = n -> n == 0 ? 0 :
|
||||
n == 1 ? 1 :
|
||||
fib.call(n - 1) + fib.call(n - 2);
|
||||
}
|
||||
int fibonacci(int n) { return fib.call(n); }
|
||||
public static void main(String[] args) {
|
||||
RecursiveFibonacci rf = new RecursiveFibonacci();
|
||||
for(int i = 0; i <= 10; i++)
|
||||
System.out.println(rf.fibonacci(i));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
0
|
||||
1
|
||||
1
|
||||
2
|
||||
3
|
||||
5
|
||||
8
|
||||
13
|
||||
21
|
||||
34
|
||||
55
|
||||
*/
|
@ -2,38 +2,32 @@
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Demonstrates method references
|
||||
// Method references with interface Runnable
|
||||
|
||||
class External {
|
||||
static void go() { System.out.println("External.go()"); }
|
||||
class Go {
|
||||
static void go() {
|
||||
System.out.println("Go::go()");
|
||||
}
|
||||
}
|
||||
|
||||
public class RunnableMethodReference {
|
||||
Runnable robject, rstatic, rexstatic;
|
||||
void f() { System.out.println("f()"); }
|
||||
static void g() { System.out.println("g()"); }
|
||||
public void assign() {
|
||||
robject = this::f;
|
||||
rstatic = RunnableMethodReference::g;
|
||||
rexstatic = External::go;
|
||||
}
|
||||
public void call() {
|
||||
robject.run();
|
||||
rstatic.run();
|
||||
rexstatic.run();
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
RunnableMethodReference rmr =
|
||||
new RunnableMethodReference();
|
||||
rmr.assign();
|
||||
rmr.call();
|
||||
rmr.robject = rmr::f;
|
||||
rmr.robject.run();
|
||||
|
||||
new Thread(new Runnable() {
|
||||
public void run() {
|
||||
System.out.println("Anonymous");
|
||||
}
|
||||
}).start();
|
||||
|
||||
new Thread(
|
||||
() -> System.out.println("lambda")
|
||||
).start();
|
||||
|
||||
new Thread(Go::go).start();
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
f()
|
||||
g()
|
||||
External.go()
|
||||
f()
|
||||
Anonymous
|
||||
lambda
|
||||
Go::go()
|
||||
*/
|
||||
|
22
functional/SharedStorage.java
Normal file
22
functional/SharedStorage.java
Normal file
@ -0,0 +1,22 @@
|
||||
// functional/SharedStorage.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
public class SharedStorage {
|
||||
public static void main(String[] args) {
|
||||
Closure1 c1 = new Closure1();
|
||||
IntSupplier f1 = c1.make_fun(0);
|
||||
IntSupplier f2 = c1.make_fun(0);
|
||||
IntSupplier f3 = c1.make_fun(0);
|
||||
System.out.println(f1.getAsInt());
|
||||
System.out.println(f2.getAsInt());
|
||||
System.out.println(f3.getAsInt());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
0
|
||||
1
|
||||
2
|
||||
*/
|
@ -4,44 +4,55 @@
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
interface Strategy {
|
||||
String variant(String arg);
|
||||
}
|
||||
|
||||
class Loud implements Strategy {
|
||||
public String variant(String arg) {
|
||||
return arg.toUpperCase() + "!";
|
||||
}
|
||||
String approach(String msg);
|
||||
}
|
||||
|
||||
class Soft implements Strategy {
|
||||
public String variant(String arg) {
|
||||
return arg.toLowerCase() + "?";
|
||||
public String approach(String msg) {
|
||||
return msg.toLowerCase() + "?";
|
||||
}
|
||||
}
|
||||
|
||||
class Unrelated {
|
||||
static String twice(String msg) {
|
||||
return msg + " " + msg;
|
||||
}
|
||||
}
|
||||
|
||||
public class Strategize {
|
||||
private Strategy strategy;
|
||||
public Strategize(Strategy strat) { strategy = strat; }
|
||||
public void communicate(String msg) {
|
||||
System.out.println(strategy.variant(msg));
|
||||
Strategy strategy;
|
||||
String msg;
|
||||
Strategize(String msg) {
|
||||
strategy = new Soft(); // (1)
|
||||
this.msg = msg;
|
||||
}
|
||||
void communicate() {
|
||||
System.out.println(strategy.approach(msg));
|
||||
}
|
||||
void changeStrategy(Strategy strategy) {
|
||||
this.strategy = strategy;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
String msg = "Hello there";
|
||||
Strategize[] approaches = {
|
||||
new Strategize(new Loud()),
|
||||
new Strategize(new Soft()),
|
||||
new Strategize(new Strategy() {
|
||||
public String variant(String arg) {
|
||||
return arg.substring(0, 5);
|
||||
Strategy[] strategies = {
|
||||
new Strategy() { // (2)
|
||||
public String approach(String msg) {
|
||||
return msg.toUpperCase() + "!";
|
||||
}
|
||||
})
|
||||
},
|
||||
msg -> msg.substring(0, 5), // (3)
|
||||
Unrelated::twice // (4)
|
||||
};
|
||||
for(Strategize approach : approaches)
|
||||
approach.communicate(msg);
|
||||
Strategize s = new Strategize("Hello there");
|
||||
s.communicate();
|
||||
for(Strategy newStrategy : strategies) {
|
||||
s.changeStrategy(newStrategy); // (5)
|
||||
s.communicate(); // (6)
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
HELLO THERE!
|
||||
hello there?
|
||||
HELLO THERE!
|
||||
Hello
|
||||
Hello there Hello there
|
||||
*/
|
||||
|
35
functional/TransformFunction.java
Normal file
35
functional/TransformFunction.java
Normal file
@ -0,0 +1,35 @@
|
||||
// functional/TransformFunction.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
import java.util.function.*;
|
||||
|
||||
class I {
|
||||
@Override
|
||||
public String toString() { return "I"; }
|
||||
}
|
||||
|
||||
class O {
|
||||
@Override
|
||||
public String toString() { return "O"; }
|
||||
}
|
||||
|
||||
public class TransformFunction {
|
||||
static Function<I,O> transform(Function<I,O> in) {
|
||||
return in.andThen(o -> {
|
||||
System.out.println(o);
|
||||
return o;
|
||||
});
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
Function<I,O> f2 = transform(i -> {
|
||||
System.out.println(i);
|
||||
return new O();
|
||||
});
|
||||
O o = f2.apply(new I());
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
I
|
||||
O
|
||||
*/
|
9
functional/TriFunction.java
Normal file
9
functional/TriFunction.java
Normal file
@ -0,0 +1,9 @@
|
||||
// functional/TriFunction.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
@FunctionalInterface
|
||||
public interface TriFunction<T, U, V, R> {
|
||||
R apply(T t, U u, V v);
|
||||
}
|
13
functional/TriFunctionTest.java
Normal file
13
functional/TriFunctionTest.java
Normal file
@ -0,0 +1,13 @@
|
||||
// functional/TriFunctionTest.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
|
||||
public class TriFunctionTest {
|
||||
static int f(int i, long l, double d) { return 99; }
|
||||
public static void main(String[] args) {
|
||||
TriFunction<Integer, Long, Double, Integer> tf =
|
||||
TriFunctionTest::f;
|
||||
tf = (i, l, d) -> 12;
|
||||
}
|
||||
}
|
@ -3,30 +3,29 @@
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Method reference without an object.
|
||||
import java.util.*;
|
||||
import java.util.function.*;
|
||||
|
||||
class X {
|
||||
String f() { return "X.f()"; }
|
||||
String f() { return "X::f()"; }
|
||||
}
|
||||
|
||||
interface MakeString {
|
||||
String make();
|
||||
}
|
||||
|
||||
interface TransformX {
|
||||
String transform(X x);
|
||||
}
|
||||
|
||||
public class UnboundMethodReference {
|
||||
public static void main(String[] args) {
|
||||
Function<String, Integer> len = String::length;
|
||||
System.out.println(len.apply("UnboundMethodReference"));
|
||||
|
||||
List<String> words =
|
||||
Arrays.asList("Rain", "Spain", "Plain");
|
||||
words.forEach(System.out::println);
|
||||
|
||||
Function<X, String> xfr = X::f;
|
||||
System.out.println(xfr.apply(new X()));
|
||||
// MakeString ms = X::f; // (1)
|
||||
TransformX sp = X::f;
|
||||
X x = new X();
|
||||
System.out.println(sp.transform(x)); // (2)
|
||||
System.out.println(x.f()); // Same effect
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
22
|
||||
Rain
|
||||
Spain
|
||||
Plain
|
||||
X.f()
|
||||
X::f()
|
||||
X::f()
|
||||
*/
|
||||
|
@ -1,36 +0,0 @@
|
||||
// functional/arr/ArgReturnReferences.java
|
||||
// ©2016 MindView LLC: see Copyright.txt
|
||||
// We make no guarantees that this code is fit for any purpose.
|
||||
// Visit http://mindviewinc.com/Books/OnJava/ for more book information.
|
||||
// Demonstrates method references
|
||||
package functional.arr;
|
||||
import java.util.function.*;
|
||||
|
||||
class Y {
|
||||
static Y create() { return new Y(); }
|
||||
static void absorb(Y y) {}
|
||||
static String transform1(Y y) { return "Y"; }
|
||||
static String transform2(Y y, String s) {
|
||||
return "Y" + " " + s;
|
||||
}
|
||||
}
|
||||
|
||||
public class ArgReturnReferences {
|
||||
Supplier<Y> supply = Y::create;
|
||||
Consumer<Y> consume = Y::absorb;
|
||||
Function<Y, String> f1arg = Y::transform1;
|
||||
BiFunction<Y, String, String> f2arg =
|
||||
Y::transform2;
|
||||
public static void main(String[] args) {
|
||||
ArgReturnReferences arr =
|
||||
new ArgReturnReferences();
|
||||
Y y = arr.supply.get();
|
||||
arr.consume.accept(y);
|
||||
System.out.println(arr.f1arg.apply(y));
|
||||
System.out.println(arr.f2arg.apply(y, "Howdy"));
|
||||
}
|
||||
}
|
||||
/* Output:
|
||||
Y
|
||||
Y Howdy
|
||||
*/
|
@ -2,21 +2,37 @@
|
||||
|
||||
<project default="run">
|
||||
<property name="chapter" value="functional"/>
|
||||
<property name="excludedfiles" value=""/>
|
||||
<property name="excludedfiles" value="Closure3.java Closure5.java Closure7.java Closure9.java"/>
|
||||
<import file="../Ant-Common.xml"/>
|
||||
<import file="../Ant-Clean.xml"/>
|
||||
|
||||
<target name="run" description="Compile and run" depends="build">
|
||||
<jrun cls="BiConsumerPermutations" />
|
||||
<jrun cls="ClassFunctionals" />
|
||||
<jrun cls="Closure8" />
|
||||
<jrun cls="ConsumeFunction" />
|
||||
<jrun cls="CtorReference" />
|
||||
<jrun cls="CurryingAndPartialFunctionApplication" />
|
||||
<jrun cls="Factories" />
|
||||
<jrun cls="Games" />
|
||||
<jrun cls="CurriedIntAdd" />
|
||||
<jrun cls="Curry3Args" />
|
||||
<jrun cls="CurryingAndPartials" />
|
||||
<jrun cls="FunctionalAnnotation" />
|
||||
<jrun cls="FunctionComposition" />
|
||||
<jrun cls="FunctionVariants" />
|
||||
<jrun cls="FunctionWithWrapped" />
|
||||
<jrun cls="LambdaExpressions" />
|
||||
<jrun cls="MethodConversion" />
|
||||
<jrun cls="MethodReferences" />
|
||||
<jrun cls="MultiUnbound" />
|
||||
<jrun cls="PredicateComposition" />
|
||||
<jrun cls="ProduceFunction" />
|
||||
<jrun cls="RecursiveFactorial" />
|
||||
<jrun cls="RecursiveFibonacci" />
|
||||
<jrun cls="RunnableMethodReference" />
|
||||
<jrun cls="SharedStorage" />
|
||||
<jrun cls="Strategize" />
|
||||
<jrun cls="TransformFunction" />
|
||||
<jrun cls="TriFunctionTest" />
|
||||
<jrun cls="UnboundMethodReference" />
|
||||
<jrun cls="functional.arr.ArgReturnReferences" dirpath="../functional/arr" />
|
||||
</target>
|
||||
|
||||
</project>
|
||||
|
@ -22,7 +22,9 @@ public class Apply {
|
||||
}
|
||||
|
||||
class Shape {
|
||||
public void rotate() { System.out.println(this + " rotate"); }
|
||||
public void rotate() {
|
||||
System.out.println(this + " rotate");
|
||||
}
|
||||
public void resize(int newSize) {
|
||||
System.out.println(this + " resize " + newSize);
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user