repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P263_BlockingEchoServer/src/main/java/modern/challenge/Main.java
Chapter13/P263_BlockingEchoServer/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.StandardProtocolFamily; import java.nio.channels.DatagramChannel; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; public class Main { private static final int SERVER_PORT = 4444; private static final String SERVER_IP = "127.0.0.1"; // modify this to your local IP private static final int MAX_SIZE_OF_PACKET = 65507; public static void main(String[] args) { ByteBuffer echoBuffer = ByteBuffer.allocateDirect(MAX_SIZE_OF_PACKET); // create a datagram channel try (DatagramChannel dchannel = DatagramChannel.open(StandardProtocolFamily.INET)) { // if the channel was successfully opened if (dchannel.isOpen()) { System.out.println("The echo server is ready!"); // optionally, configure the server side options dchannel.setOption(StandardSocketOptions.SO_RCVBUF, 4 * 1024); dchannel.setOption(StandardSocketOptions.SO_SNDBUF, 4 * 1024); // bind the channel to local address dchannel.bind(new InetSocketAddress(SERVER_IP, SERVER_PORT)); System.out.println("Echo server available at: " + dchannel.getLocalAddress()); System.out.println("Ready to echo ..."); // sending data packets while (true) { SocketAddress clientSocketAddress = dchannel.receive(echoBuffer); echoBuffer.flip(); System.out.println("Received " + echoBuffer.limit() + " bytes from " + clientSocketAddress.toString() + "! Echo ..."); dchannel.send(echoBuffer, clientSocketAddress); echoBuffer.clear(); } } else { System.out.println("The channel is unavailable!"); } } catch (SecurityException | IOException ex) { System.err.println(ex); // handle exception } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P271_ProgrammaticSWS/src/main/java/modern/challenge/Main.java
Chapter13/P271_ProgrammaticSWS/src/main/java/modern/challenge/Main.java
package modern.challenge; import com.sun.net.httpserver.HttpServer; import com.sun.net.httpserver.SimpleFileServer; import com.sun.net.httpserver.SimpleFileServer.OutputLevel; import java.net.InetSocketAddress; import java.nio.file.Path; public class Main { public static void main(String[] args) { HttpServer sws = SimpleFileServer.createFileServer( new InetSocketAddress(9009), Path.of("./docs").toAbsolutePath(), OutputLevel.VERBOSE); sws.start(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter13/P266_MulticastClient/src/main/java/modern/challenge/Main.java
Chapter13/P266_MulticastClient/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.StandardProtocolFamily; import java.nio.channels.DatagramChannel; import java.net.StandardSocketOptions; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.channels.MembershipKey; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; public class Main { private static final int SERVER_PORT = 4444; private static final int MAX_SIZE_OF_PACKET = 65507; private static final String MULTICAST_GROUP = "225.4.5.6"; private static final String MULTICAST_NI_NAME = "ethernet_32775"; public static void main(String[] args) { CharBuffer cBuffer; Charset charset = Charset.defaultCharset(); CharsetDecoder chdecoder = charset.newDecoder(); ByteBuffer dtBuffer = ByteBuffer.allocateDirect(MAX_SIZE_OF_PACKET); // create a channel try (DatagramChannel dchannel = DatagramChannel.open(StandardProtocolFamily.INET)) { InetAddress multigroup = InetAddress.getByName(MULTICAST_GROUP); // if the group address is multicast if (multigroup.isMulticastAddress()) { // if the channel was successfully open if (dchannel.isOpen()) { // get the multicast network interface NetworkInterface mni = NetworkInterface.getByName(MULTICAST_NI_NAME); // optionally, configure the client side options dchannel.setOption(StandardSocketOptions.SO_REUSEADDR, true); // bind the channel to remote address dchannel.bind(new InetSocketAddress(SERVER_PORT)); // join the multicast group and receive datagrams MembershipKey memkey = dchannel.join(multigroup, mni); // wait to receive datagrams while (true) { if (memkey.isValid()) { dchannel.receive(dtBuffer); dtBuffer.flip(); cBuffer = chdecoder.decode(dtBuffer); System.out.println(cBuffer.toString()); dtBuffer.clear(); } else { break; } } } else { System.out.println("The channel is unavailable!"); } } else { System.out.println("Not a multicast address!"); } } catch (IOException ex) { System.err.println(ex); // handle exception } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P115_FactoryMethodsForCollections/src/main/java/modern/challenge/Main.java
Chapter05/P115_FactoryMethodsForCollections/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import static java.util.Map.entry; import java.util.Set; import static java.util.stream.Collectors.collectingAndThen; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import java.util.stream.Stream; public class Main { public static void main(String[] args) { // Map // ///////// // before JDK 9 Map<Integer, String> map = new HashMap<>(); map.put(1, "Java Coding Problems, First Edition"); map.put(2, "The Complete Coding Interview Guide in Java"); map.put(3, "jOOQ Masterclass"); // map.put(4, null); // null values are allowed // map.put(null, "Java Coding Problems, Second Edition"); Map<Integer, String> imap1 = Collections.unmodifiableMap(map); // imap1.put(5, "Java Coding Problems, Second Edition"); // UnsupportedOperationException Map<Integer, String> imap2 = Collections.unmodifiableMap(new HashMap<Integer, String>() { { put(1, "Java Coding Problems, First Edition"); put(2, "The Complete Coding Interview Guide in Java"); put(3, "jOOQ Masterclass"); put(4, null); put(null, "Java Coding Problems, Second Edition"); } }); // imap2.put(5, "Java Coding Problems, Second Edition"); // UnsupportedOperationException Map<Integer, String> imap3 = Stream.of( entry(1, "Java Coding Problems, First Edition"), entry(2, "The Complete Coding Interview Guide in Java"), entry(3, "jOOQ Masterclass")) .collect(collectingAndThen(toMap(e -> e.getKey(), e -> e.getValue()), Collections::unmodifiableMap)); // imap3.put(5, "Java Coding Problems, Second Edition"); // UnsupportedOperationException Map<Integer, String> imap4 = Collections.emptyMap(); // imap4.put(1, "Java Coding Problems, First Edition"); // UnsupportedOperationException Map<Integer, String> imap5 = Collections.singletonMap(1, "Java Coding Problems, First Edition"); // imap5.put(2, "The Complete Coding Interview Guide in Java"); // UnsupportedOperationException // JDK 9+ Map<Integer, String> imap1jdk9 = Map.of( 1, "Java Coding Problems, First Edition", 2, "The Complete Coding Interview Guide in Java", 3, "jOOQ Masterclass" // 4, null // NullPointerException // null, "Java Coding Problems, Second Edition" // NullPointerException ); Map<Integer, String> imap2jdk9 = Map.ofEntries( entry(1, "Java Coding Problems, First Edition"), entry(2, "The Complete Coding Interview Guide in Java"), entry(3, "jOOQ Masterclass") // entry(4, null) // NullPointerException // entry(null, "Java Coding Problems, Second Edition") // NullPointerException ); // imap1jdk9.put(5, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // imap2jdk9.put(5, "Java Coding Problems, Second Edition"); // UnsupportedOperationException Map<Integer, String> imap3jdk9 = Map.copyOf(imap1jdk9); Map<Integer, String> imap4jdk9 = Map.copyOf(map); System.out.println("Equal maps (1): " + (imap1jdk9 == imap3jdk9)); // true System.out.println("Equal maps (2): " + (imap4jdk9 == map)); // false Map<Integer, String> im1 = Map.of(1, "1", 2, "2"); Map<Integer, String> im2 = Map.of(1, "1", 2, "2"); System.out.println("Equal maps (3): " + (im1 == im2)); // false // List // ////////// // before JDK 9 List<String> list = new ArrayList<>(); list.add("Java Coding Problems, First Edition"); list.add("The Complete Coding Interview Guide in Java"); list.add("jOOQ Masterclass"); list.add(null); // null values are allowed List<String> ilist1 = Collections.unmodifiableList(list); // ilist1.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // ilist1.set(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException List<String> ilist2 = Arrays.asList( "Java Coding Problems, First Edition", "The Complete Coding Interview Guide in Java", "jOOQ Masterclass" ); // ilist2.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException ilist2.set(0, "Java Coding Problems, Second Edition"); List<String> ilist3 = Stream.of( "Java Coding Problems, First Edition", "The Complete Coding Interview Guide in Java", "jOOQ Masterclass") .collect(collectingAndThen(toList(), Collections::unmodifiableList)); // ilist3.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // ilist3.set(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException List<String> ilist4 = Collections.emptyList(); // ilist4.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // ilist4.set(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException List<String> ilist5 = Collections.singletonList("Java Coding Problems, First Edition"); // ilist5.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // ilist5.set(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // JDK 9+ List<String> ilist1jdk9 = List.of( "Java Coding Problems, First Edition", "The Complete Coding Interview Guide in Java", "jOOQ Masterclass"); // null); // NullPointerException // ilist1jdk9.add(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException // ilist1jdk9.set(0, "Java Coding Problems, Second Edition"); // UnsupportedOperationException List<String> ilist2jdk9 = List.copyOf(ilist1jdk9); System.out.println("Equal lists: " + (ilist1jdk9 == ilist2jdk9)); // true // Set // ////////// // before JDK 9 Set<String> set = new HashSet<>(); set.add("Java Coding Problems, First Edition"); set.add("The Complete Coding Interview Guide in Java"); set.add("jOOQ Masterclass"); set.add(null); // null values are allowed Set<String> iset1 = Collections.unmodifiableSet(set); // iset1.remove("Java Coding Problems, First Edition"); // UnsupportedOperationException Set<String> iset2 = Stream.of( "Java Coding Problems, First Edition", "The Complete Coding Interview Guide in Java", "jOOQ Masterclass") .collect(collectingAndThen(toSet(), Collections::unmodifiableSet)); // iset2.remove("Java Coding Problems, First Edition"); // UnsupportedOperationException Set<String> iset3 = Collections.emptySet(); // iset3.add("Java Coding Problems, First Edition"); // UnsupportedOperationException Set<String> iset4 = Collections.singleton("Java Coding Problems, First Edition"); // iset4.remove("Java Coding Problems, First Edition"); // UnsupportedOperationException // JDK 9+ Set<String> iset1jdk9 = Set.of( "Java Coding Problems, First Edition", "The Complete Coding Interview Guide in Java", "jOOQ Masterclass"); // null); // NullPointerException // iset1jdk9.remove("Java Coding Problems, First Edition"); // UnsupportedOperationException Set<String> iset2jdk9 = Set.copyOf(iset1jdk9); System.out.println("Equal sets: " + (iset1jdk9 == iset2jdk9)); // true } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P109_SummingArrays/src/main/java/module-info.java
Chapter05/P109_SummingArrays/src/main/java/module-info.java
module P109_SummingArrays { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P109_SummingArrays/src/main/java/modern/challenge/Main.java
Chapter05/P109_SummingArrays/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Arrays; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorMask; import jdk.incubator.vector.VectorSpecies; public class Main { private static final VectorSpecies<Integer> VS256 = IntVector.SPECIES_256; public static void sum(int x[], int y[], int z[]) { int upperBound = VS256.loopBound(x.length); for (int i = 0; i < upperBound; i += VS256.length()) { IntVector xVector = IntVector.fromArray(VS256, x, i); IntVector yVector = IntVector.fromArray(VS256, y, i); IntVector zVector = xVector.add(yVector); zVector.intoArray(z, i); } } public static void sumMask(int x[], int y[], int z[]) { int upperBound = VS256.loopBound(x.length); int i = 0; for (; i < upperBound; i += VS256.length()) { IntVector xVector = IntVector.fromArray(VS256, x, i); IntVector yVector = IntVector.fromArray(VS256, y, i); IntVector zVector = xVector.add(yVector); zVector.intoArray(z, i); } if (i <= (x.length - 1)) { VectorMask<Integer> mask = VS256.indexInRange(i, x.length); IntVector zVector = IntVector.fromArray(VS256, x, i, mask) .add(IntVector.fromArray(VS256, y, i, mask)); zVector.intoArray(z, i, mask); } } public static void sumPlus(int x[], int y[], int z[]) { int upperBound = VS256.loopBound(x.length); int i = 0; for (; i < upperBound; i += VS256.length()) { IntVector xVector = IntVector.fromArray(VS256, x, i); IntVector yVector = IntVector.fromArray(VS256, y, i); IntVector zVector = xVector.add(yVector); zVector.intoArray(z, i); } for (; i < x.length; i++) { z[i] = x[i] + y[i]; } } public static void main(String[] args) { int[] x = new int[]{3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 3, 4}; int[] y = new int[]{4, 5, 2, 5, 1, 3, 8, 7, 1, 6, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 2, 8}; int[] z = new int[x.length]; sum(x, y, z); System.out.println("Result: " + Arrays.toString(z)); z = new int[x.length]; sumMask(x, y, z); System.out.println("Result: " + Arrays.toString(z)); z = new int[x.length]; sumPlus(x, y, z); System.out.println("Result: " + Arrays.toString(z)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P118_SequencedCollectionsRemove/src/main/java/modern/challenge/Main.java
Chapter05/P118_SequencedCollectionsRemove/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.SequencedMap; import java.util.SequencedSet; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { // ArrayList List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 list.remove(0); // remove the first element list.remove(list.size() - 1); // remove the last element // list.remove("five"); // JDK 21 list.removeFirst(); list.removeLast(); // LinkedList List<String> linkedlist = new LinkedList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 linkedlist.remove(0); linkedlist.remove("five"); // JDK 21 linkedlist.removeFirst(); linkedlist.removeLast(); // LinkedHashSet SequencedSet<String> linkedhashset = new LinkedHashSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 linkedhashset.remove("one"); linkedhashset.remove("five"); // or, use the code for getting the first/last elements and call remove on those // JDK 21 linkedhashset.removeFirst(); linkedhashset.removeLast(); // SortedSet SortedSet<String> sortedset = new TreeSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 String first = sortedset.first(); sortedset.remove(first); String last = sortedset.last(); sortedset.remove(last); // JDK 21 sortedset.removeFirst(); sortedset.removeLast(); // LinkedHashMap SequencedMap<Integer, String> linkedhashmap = new LinkedHashMap<>(); linkedhashmap.put(1, "one"); linkedhashmap.put(2, "two"); linkedhashmap.put(3, "three"); linkedhashmap.put(4, "four"); linkedhashmap.put(5, "five"); // before JDK 21 // linkedhashmap.remove(1); // linkedhashmap.remove(5, "five"); Entry<Integer, String> firstentrylhm = linkedhashmap.entrySet().iterator().next(); linkedhashmap.remove(firstentrylhm.getKey()); linkedhashmap.remove(firstentrylhm.getKey(), firstentrylhm.getValue()); Entry<Integer, String> lastEntryLhm = linkedhashmap.entrySet().stream() .skip(linkedhashmap.size() - 1).findFirst().get(); linkedhashmap.remove(lastEntryLhm.getKey()); linkedhashmap.remove(lastEntryLhm.getKey(), lastEntryLhm.getValue()); // JDK 21 linkedhashmap.pollFirstEntry(); linkedhashmap.pollLastEntry(); // SortedMap SortedMap<Integer, String> sortedmap = new TreeMap<>(); sortedmap.put(1, "one"); sortedmap.put(2, "two"); sortedmap.put(3, "three"); sortedmap.put(4, "four"); sortedmap.put(5, "five"); // before JDK 21 // sortedmap.remove(1); // sortedmap.remove(5, "five"); Integer fkey = sortedmap.firstKey(); String fval = sortedmap.get(fkey); Integer lkey = sortedmap.lastKey(); String lval = sortedmap.get(lkey); sortedmap.remove(fkey); sortedmap.remove(fkey, fval); sortedmap.remove(lkey); sortedmap.remove(lkey, lval); // JDK 21 sortedmap.pollFirstEntry(); sortedmap.pollLastEntry(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P118_SequencedCollectionsGetFirstLast/src/main/java/modern/challenge/Main.java
Chapter05/P118_SequencedCollectionsGetFirstLast/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Map.Entry; import java.util.SequencedCollection; import java.util.SequencedMap; import java.util.SequencedSet; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { // ArrayList List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 String firstl = list.get(0); // one String lastl = list.get(list.size() - 1); // five // JDK 21 String firstl21 = list.getFirst(); // one String lastl21 = list.getLast(); // five // LinkedList List<String> linkedlist = new LinkedList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 String firstll = linkedlist.get(0); // one String lastll = linkedlist.get(list.size() - 1); // five // JDK 21 String firstll21 = linkedlist.getFirst(); // one String lastll21 = linkedlist.getLast(); // five // LinkedHashSet SequencedSet<String> linkedhashset = new LinkedHashSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 linkedhashset.iterator().next(); linkedhashset.stream().findFirst().get(); linkedhashset.stream().skip(linkedhashset.size() - 1).findFirst().get(); String last = (String) linkedhashset.toArray()[linkedhashset.size() - 1]; // JDK 21 linkedhashset.getFirst(); linkedhashset.getLast(); // SortedSet SortedSet<String> sortedset = new TreeSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 sortedset.first(); sortedset.last(); // JDK 21 sortedset.getFirst(); sortedset.getLast(); // LinkedHashMap SequencedMap<Integer, String> linkedhashmap = new LinkedHashMap<>(); linkedhashmap.put(1, "one"); linkedhashmap.put(2, "two"); linkedhashmap.put(3, "three"); linkedhashmap.put(4, "four"); linkedhashmap.put(5, "five"); // before JDK 21 linkedhashmap.keySet().iterator().next(); linkedhashmap.keySet().stream().findFirst().get(); linkedhashmap.keySet().stream().skip(linkedhashmap.size() - 1).findFirst().get(); Integer lastKeyLhm = (Integer) linkedhashmap.keySet().toArray()[linkedhashmap.size() - 1]; linkedhashmap.values().iterator().next(); linkedhashmap.values().stream().findFirst().get(); linkedhashmap.values().stream().skip(linkedhashmap.size() - 1).findFirst().get(); String lastValueLhm = (String) linkedhashmap.values().toArray()[linkedhashmap.size() - 1]; linkedhashmap.entrySet().iterator().next(); linkedhashmap.entrySet().stream().findFirst().get(); linkedhashmap.entrySet().stream().skip(linkedhashmap.size() - 1).findFirst().get(); Entry<Integer, String> lastEntryLhm = (Entry<Integer, String>) linkedhashmap.entrySet().toArray()[linkedhashmap.size() - 1]; // JDK 21 Entry<Integer, String> fe = linkedhashmap.firstEntry(); Entry<Integer, String> le = linkedhashmap.lastEntry(); SequencedSet<Integer> keysLinkedHashMap = linkedhashmap.sequencedKeySet(); keysLinkedHashMap.getFirst(); keysLinkedHashMap.getLast(); SequencedCollection<String> valuesLinkedHashMap = linkedhashmap.sequencedValues(); valuesLinkedHashMap.getFirst(); valuesLinkedHashMap.getLast(); SequencedSet<Entry<Integer, String>> entriesLinkedHashMap = linkedhashmap.sequencedEntrySet(); entriesLinkedHashMap.getFirst(); entriesLinkedHashMap.getLast(); // SortedMap SortedMap<Integer, String> sortedmap = new TreeMap<>(); sortedmap.put(1, "one"); sortedmap.put(2, "two"); sortedmap.put(3, "three"); sortedmap.put(4, "four"); sortedmap.put(5, "five"); // before JDK 21 Integer fkey = sortedmap.firstKey(); String fval = sortedmap.get(fkey); Integer lkey = sortedmap.lastKey(); String lval = sortedmap.get(lkey); // JDK 21 sortedmap.firstEntry(); sortedmap.firstEntry().getKey(); sortedmap.firstEntry().getValue(); sortedmap.lastEntry(); sortedmap.lastEntry().getKey(); sortedmap.lastEntry().getValue(); SequencedSet<Integer> keysSortedMap = sortedmap.sequencedKeySet(); keysSortedMap.getFirst(); keysSortedMap.getLast(); SequencedCollection<String> valuesSortedMap = sortedmap.sequencedValues(); valuesSortedMap.getFirst(); valuesSortedMap.getLast(); SequencedSet<Entry<Integer, String>> entriesSortedMap = sortedmap.sequencedEntrySet(); entriesSortedMap.getFirst(); entriesSortedMap.getLast(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P112_VectorApiAndFma/src/main/java/module-info.java
Chapter05/P112_VectorApiAndFma/src/main/java/module-info.java
module P112_VectorApiAndFma { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P112_VectorApiAndFma/src/main/java/modern/challenge/Main.java
Chapter05/P112_VectorApiAndFma/src/main/java/modern/challenge/Main.java
package modern.challenge; import jdk.incubator.vector.FloatVector; import jdk.incubator.vector.VectorMask; import jdk.incubator.vector.VectorOperators; import jdk.incubator.vector.VectorSpecies; public class Main { private static final VectorSpecies<Float> VS = FloatVector.SPECIES_PREFERRED; public static float vectorFma(float[] x, float[] y) { int upperBound = VS.loopBound(x.length); FloatVector sum = FloatVector.zero(VS); int i = 0; for (; i < upperBound; i += VS.length()) { FloatVector xVector = FloatVector.fromArray(VS, x, i); FloatVector yVector = FloatVector.fromArray(VS, y, i); sum = xVector.fma(yVector, sum); // sum = xVector.mul(yVector).add(sum) } if (i <= (x.length - 1)) { VectorMask<Float> mask = VS.indexInRange(i, x.length); FloatVector xVector = FloatVector.fromArray(VS, x, i, mask); FloatVector yVector = FloatVector.fromArray(VS, y, i, mask); sum = xVector.fma(yVector, sum); } float result = sum.reduceLanes(VectorOperators.ADD); return result; } public static void main(String[] args) { float[] x = new float[]{1f, 2f, 3f, 5f, 1f, 8f}; float[] y = new float[]{4f, 5f, 2f, 8f, 5f, 4f}; float result = vectorFma(x, y); System.out.println("Fma result: " + result); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P108_VectorTerminology/src/main/java/module-info.java
Chapter05/P108_VectorTerminology/src/main/java/module-info.java
module P108_VectorTerminology { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P108_VectorTerminology/src/main/java/modern/challenge/Main.java
Chapter05/P108_VectorTerminology/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.lang.foreign.MemorySegment; import java.lang.foreign.Arena; import java.lang.foreign.ValueLayout; import java.nio.ByteOrder; import java.util.Arrays; import jdk.incubator.vector.DoubleVector; import jdk.incubator.vector.FloatVector; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.Vector; import jdk.incubator.vector.VectorMask; import jdk.incubator.vector.VectorOperators; import jdk.incubator.vector.VectorShape; import jdk.incubator.vector.VectorShuffle; import jdk.incubator.vector.VectorSpecies; public class Main { public static void main(String[] args) { // examples of creating VectorSpecies VectorSpecies<Double> VS1 = VectorSpecies.of(double.class, VectorShape.S_512_BIT); VectorSpecies<Double> VS2 = VectorSpecies.of(double.class, VectorShape.S_Max_BIT); VectorSpecies<Double> VS3 = VectorSpecies.ofLargestShape(double.class); VectorSpecies<Double> VS4 = VectorSpecies.ofPreferred(double.class); VectorSpecies<Double> VS5 = DoubleVector.SPECIES_512; VectorSpecies<Double> VS6 = DoubleVector.SPECIES_MAX; VectorSpecies<Double> VS7 = DoubleVector.SPECIES_PREFERRED; // print the element type and shape for VS System.out.println("Element type (VS1): " + VS1.elementType()); System.out.println("Shape (VS1): " + VS1.vectorShape()); System.out.println("Element type (VS2): " + VS2.elementType()); System.out.println("Shape (VS2): " + VS2.vectorShape()); System.out.println("Element type (VS3): " + VS3.elementType()); System.out.println("Shape (VS3): " + VS3.vectorShape()); System.out.println("Element type (VS4): " + VS4.elementType()); System.out.println("Shape (VS4): " + VS4.vectorShape()); System.out.println("Element type (VS5): " + VS5.elementType()); System.out.println("Shape (VS5): " + VS5.vectorShape()); System.out.println("Element type (VS6): " + VS6.elementType()); System.out.println("Shape (VS6): " + VS6.vectorShape()); System.out.println("Element type (VS7): " + VS7.elementType()); System.out.println("Shape (VS7): " + VS7.vectorShape()); System.out.println(); // getting length (number of lanes/scalars) VectorSpecies<Float> VSF = FloatVector.SPECIES_256; System.out.println("Length: " + VSF.length()); System.out.println("Length: " + VSF.vectorBitSize()/VSF.elementSize()); System.out.println(); // creating vectors VectorSpecies<Integer> VS256 = IntVector.SPECIES_256; // creating vectors of zeros Vector<Integer> v1 = VS256.zero(); System.out.println("v1: " + Arrays.toString(v1.toIntArray())); IntVector v2 = IntVector.zero(VS256); System.out.println("v2: " + Arrays.toString(v2.toIntArray())); // creating vectors of same primitive value Vector<Integer> v3 = VS256.broadcast(5); System.out.println("v3: " + Arrays.toString(v3.toIntArray())); IntVector v4 = IntVector.broadcast(VS256, 5); System.out.println("v4: " + Arrays.toString(v4.toIntArray())); IntVector v5 = IntVector.broadcast(VS256, 0); System.out.println("v5: " + Arrays.toString(v5.toIntArray())); // fromArray() int[] varr1 = new int[] {0, 1, 2, 3, 4, 5, 6, 7}; Vector<Integer> vfa1 = VS256.fromArray(varr1, 0); System.out.println("vfa1: " + Arrays.toString(vfa1.toIntArray())); int[] varr2 = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; Vector<Integer> vfa2 = VS256.fromArray(varr2, 0); System.out.println("vfa2: " + Arrays.toString(vfa2.toIntArray())); int[] varr3 = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; Vector<Integer> vfa3 = VS256.fromArray(varr3, 2); System.out.println("vfa3: " + Arrays.toString(vfa3.toIntArray())); // java.lang.IndexOutOfBoundsException // int[] varr4 = new int[]{0, 1, 2, 3, 4, 5}; // IntVector vfa4 = IntVector.fromArray(VS256, varr4, 0); int[] varr5 = new int[] {0, 1, 2, 3, 4, 5, 6, 7}; IntVector vfa5 = IntVector.fromArray(VS256, varr5, 0); System.out.println("vfa5: " + Arrays.toString(vfa5.toIntArray())); int[] varr6 = new int[]{0, 1, 2, 3, 4, 5, 6, 7}; boolean[] bm1 = new boolean[]{false, false, true, false, false, true, true, false}; VectorMask m1 = VectorMask.fromArray(VS256, bm1, 0); IntVector vfa6 = IntVector.fromArray(VS256, varr6, 0, m1); System.out.println("vfa6: " + Arrays.toString(vfa6.toIntArray())); int[] varr7 = new int[]{11, 12, 15, 17, 20, 22, 29}; int[] imap1 = new int[]{0, 0, 0, 1, 1, 6, 6, 6}; IntVector vfa7 = IntVector.fromArray(VS256, varr7, 0, imap1, 0); System.out.println("vfa7: " + Arrays.toString(vfa7.toIntArray())); int[] varr8 = new int[]{11, 12, 15, 17, 20, 22, 29}; boolean[] bm2 = new boolean[]{false, false, true, false, false, true, true, false}; int[] imap2 = new int[]{0, 0, 0, 1, 1, 6, 6, 6}; VectorMask m2 = VectorMask.fromArray(VS256, bm2, 0); IntVector vfa8 = IntVector.fromArray(VS256, varr8, 0, imap2, 0, m2); System.out.println("vfa8: " + Arrays.toString(vfa8.toIntArray())); // fromMemorySegment() IntVector vfms; MemorySegment segment; try (Arena arena = Arena.ofConfined()) { segment = arena.allocate(32); segment.setAtIndex(ValueLayout.JAVA_INT, 0, 11); segment.setAtIndex(ValueLayout.JAVA_INT, 1, 21); segment.setAtIndex(ValueLayout.JAVA_INT, 2, 12); segment.setAtIndex(ValueLayout.JAVA_INT, 3, 7); segment.setAtIndex(ValueLayout.JAVA_INT, 4, 33); segment.setAtIndex(ValueLayout.JAVA_INT, 5, 1); segment.setAtIndex(ValueLayout.JAVA_INT, 6, 3); segment.setAtIndex(ValueLayout.JAVA_INT, 7, 6); vfms = IntVector.fromMemorySegment(VS256, segment, 0, ByteOrder.nativeOrder()); } System.out.println("vfms: " + Arrays.toString(vfms.toIntArray())); // slice int[] v = new int[] {10, 11, 12, 13, 14, 15, 16, 17}; Vector<Integer> vo = VS256.fromArray(v, 0); Vector<Integer> vs = vo.slice(vo.length()/2); System.out.println("Original vector: " + Arrays.toString(vo.toIntArray())); System.out.println("Sliced vector: " + Arrays.toString(vs.toIntArray())); // unslice Vector<Integer> vus = vs.unslice(4, vo, 0); System.out.println("Unsliced vector: " + Arrays.toString(vus.toIntArray())); // shuffle VectorShuffle<Integer> shuffle = VectorShuffle .fromArray(VS256, new int[] {2, 1, 3, 0, 6, 7, 5, 4}, 0); Vector<Integer> vi = vo.rearrange(shuffle); System.out.println("Shuffled vector: " + Arrays.toString(vi.toIntArray())); // expand and compress VectorMask vm = VectorMask.fromArray(VS256, new boolean[]{false, false, true, false, false, true, true, false}, 0); Vector<Integer> ve = vo.expand(vm); Vector<Integer> vc = vo.compress(vm); System.out.println("Expanded vector: " + Arrays.toString(ve.toIntArray())); System.out.println("Compressed vector: " + Arrays.toString(vc.toIntArray())); // cast shape VectorSpecies<Integer> VS512cast = IntVector.SPECIES_512; VectorSpecies<Integer> VS256cast = IntVector.SPECIES_256; VectorSpecies<Integer> VS128cast = IntVector.SPECIES_128; IntVector vs1cast = IntVector.fromArray(VS256cast, new int[] {0, 1, 2, 3, 4, 5, 6, 7}, 0); Vector<Integer> vs0cast = vs1cast.castShape(VS512cast, 0); Vector<Integer> vs2cast = vs1cast.castShape(VS128cast, 0); System.out.println("vs0cast: " + Arrays.toString(vs0cast.toIntArray())); System.out.println("vs1cast: " + Arrays.toString(vs1cast.toIntArray())); System.out.println("vs2cast: " + Arrays.toString(vs2cast.toIntArray())); // convert element type FloatVector vsfloat = FloatVector.fromArray(FloatVector.SPECIES_256, new float[] {0.5f, 1.4f, 2.2f, 3.7f, 4.3f, 5.7f, 6.7f, 7.7f}, 0); Vector<Integer> vsint = vsfloat.convert(VectorOperators.Conversion.ofCast(float.class, int.class), 0); System.out.println("vsfloat: " + vsfloat); System.out.println("vsint: " + vsint); // convert shape and element type FloatVector vsfloat256 = FloatVector.fromArray(FloatVector.SPECIES_256, new float[] {0.5f, 1.4f, 2.2f, 3.7f, 4.3f, 5.7f, 6.7f, 7.7f}, 0); Vector<Integer> vsint128 = vsfloat256.convertShape( VectorOperators.Conversion.ofCast(float.class, int.class), IntVector.SPECIES_128, 0); System.out.println("vsfloat: " + vsfloat256); System.out.println("vsint: " + vsint128); // reinterpret shape FloatVector vsfloatb = FloatVector.fromArray(FloatVector.SPECIES_256, new float[] {0.5f, 1.4f, 2.2f, 3.7f, 4.3f, 5.7f, 6.7f, 7.7f}, 0); Vector<Float> vsfloata = vsfloatb.reinterpretShape(FloatVector.SPECIES_512, 0); System.out.println("vsfloatb: " + vsfloatb); System.out.println("vsfloata: " + vsfloata); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P120_TheSkipListDS/src/main/java/modern/challenge/SkipList.java
Chapter05/P120_TheSkipListDS/src/main/java/modern/challenge/SkipList.java
package modern.challenge; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.Random; public class SkipList { private static final int MAX_NUMBER_OF_LAYERS = 10; private final Node head; private final Random rnd = new Random(); private int size; private int topLayer; private final class Node { private final Integer data; private final int layer; public Node[] next; public Node(Integer data, int layer) { this.data = data; this.layer = layer; this.next = new Node[layer + 1]; } public Integer getData() { return this.data; } @Override public String toString() { return "{ layer " + layer + " :: data " + data + " }"; } } public SkipList() { this.size = 0; this.topLayer = 1; this.head = new Node(null, MAX_NUMBER_OF_LAYERS); } public void insert(Integer data) { int layer = incrementLayerNo(); Node newNode = new Node(data, layer); Node cursorNode = head; for (int i = topLayer - 1; i >= 0; i--) { while (cursorNode.next[i] != null) { if (cursorNode.next[i].getData() > data) { break; } cursorNode = cursorNode.next[i]; } if (i <= layer) { newNode.next[i] = cursorNode.next[i]; cursorNode.next[i] = newNode; } } size++; } public boolean delete(Integer data) { Node cursorNode = head; boolean deleted = false; for (int i = topLayer - 1; i >= 0; i--) { while (cursorNode.next[i] != null) { if (cursorNode.next[i].getData() > data) { break; } if (cursorNode.next[i].getData().equals(data)) { cursorNode.next[i] = cursorNode.next[i].next[i]; deleted = true; size--; break; } cursorNode = cursorNode.next[i]; } } return deleted; } public boolean contains(Integer data) { Node cursorNode = head; for (int i = topLayer - 1; i >= 0; i--) { while (cursorNode.next[i] != null) { if (cursorNode.next[i].getData() > data) { break; } if (cursorNode.next[i].getData().equals(data)) { return true; } cursorNode = cursorNode.next[i]; } } return false; } public int getSize() { return this.size; } public void printList() { Node cursorNode = head; int layer = MAX_NUMBER_OF_LAYERS - 1; while (cursorNode.next[layer] == null && layer > 0) { layer--; } cursorNode = head; List<Node> nodes = new ArrayList<>(); while (cursorNode != null) { nodes.add(cursorNode); cursorNode = cursorNode.next[0]; } for (int i = 0; i <= layer; i++) { cursorNode = head; cursorNode = cursorNode.next[i]; System.out.print("Layer " + i + " | start |"); int layerNo = 1; while (cursorNode != null) { if (i > 0) { while (!Objects.equals(nodes.get(layerNo).getData(), cursorNode.getData())) { layerNo++; System.out.print("--------------------------"); } layerNo++; } System.out.print("---> " + cursorNode); cursorNode = cursorNode.next[i]; } System.out.println(); } } private int incrementLayerNo() { int layer = 0; boolean headFlag = true; for (int i = 0; i < MAX_NUMBER_OF_LAYERS; i++) { headFlag &= rnd.nextBoolean(); if (headFlag) { layer++; if (layer == this.topLayer) { topLayer++; break; } } else { break; } } return layer; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P120_TheSkipListDS/src/main/java/modern/challenge/Main.java
Chapter05/P120_TheSkipListDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { SkipList list = new SkipList(); list.insert(4); list.insert(3); list.insert(2); list.insert(1); list.insert(8); list.insert(5); list.insert(9); list.insert(10); list.insert(11); list.insert(34); list.printList(); System.out.println(); System.out.println("Contains 11: " + list.contains(11)); list.insert(7); list.printList(); System.out.println(); list.delete(9); list.printList(); System.out.println(); list.delete(34); list.printList(); System.out.println(); list.delete(5); list.printList(); System.out.println(); list.delete(10); list.printList(); System.out.println(); list.delete(8); list.printList(); System.out.println(); list.delete(1); list.printList(); System.out.println(); System.out.println("Found 2: " + list.contains(2)); System.out.println(); list.delete(2); list.printList(); System.out.println(); System.out.println("Found 2: " + list.contains(2)); System.out.println(); list.delete(4); list.printList(); System.out.println(); list.delete(11); list.printList(); System.out.println(); list.delete(3); list.printList(); System.out.println(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P114_NegativeEffectVectorApi/src/main/java/module-info.java
Chapter05/P114_NegativeEffectVectorApi/src/main/java/module-info.java
module P114_NegativeEffectVectorApi { requires jdk.incubator.vector; requires java.desktop; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P114_NegativeEffectVectorApi/src/main/java/modern/challenge/Main.java
Chapter05/P114_NegativeEffectVectorApi/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.nio.file.Path; import javax.imageio.ImageIO; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorOperators; import jdk.incubator.vector.VectorSpecies; public class Main { private static final VectorSpecies<Integer> VS = IntVector.SPECIES_PREFERRED; public static void negativeFilter(int pixel[], int width, int height) { for (int i = 0; i <= (width * height - VS.length()); i += VS.length()) { IntVector alphaVector = IntVector.fromArray(VS, pixel, i) .lanewise(VectorOperators.LSHR, 24).and(0xff); IntVector redVector = IntVector.fromArray(VS, pixel, i) .lanewise(VectorOperators.LSHR, 16).and(0xff); IntVector greenVector = IntVector.fromArray(VS, pixel, i) .lanewise(VectorOperators.LSHR, 8).and(0xff); IntVector blueVector = IntVector.fromArray(VS, pixel, i).and(0xff); IntVector subAlphaVector = alphaVector.lanewise(VectorOperators.LSHL, 24); IntVector subRedVector = redVector.broadcast(255).sub(redVector) .lanewise(VectorOperators.LSHL, 16); IntVector subGreenVector = greenVector.broadcast(255).sub(greenVector) .lanewise(VectorOperators.LSHL, 8); IntVector subBlueVector = blueVector.broadcast(255).sub(blueVector); IntVector resultVector = subAlphaVector.or(subRedVector) .or(subGreenVector).or(subBlueVector); resultVector.intoArray(pixel, i); } } public static void main(String[] args) throws IOException { File file = Path.of("image.png").toFile(); BufferedImage img = ImageIO.read(file); int width = img.getWidth(); int height = img.getHeight(); int[] pixel = new int[width * height]; int i = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { pixel[i] = img.getRGB(x, y); i++; } } negativeFilter(pixel, width, height); i = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { img.setRGB(x, y, pixel[i]); i++; } } File filer = Path.of("image_negative.png").toFile(); ImageIO.write(img, "png", filer); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P117_newHashMap/src/main/java/modern/challenge/Main.java
Chapter05/P117_newHashMap/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) throws Exception { // before JDK 19 Map<Integer, String> map1 = new HashMap<>(4); map1.put(1, "1"); map1.put(2, "2"); map1.put(3, "3"); // capacity: 4 map1.put(4, "4"); // capacity: 8 // emulating JDK 19 System.out.println("Emulating capacity: " + ((int) Math.ceil(4 / (double) 0.75))); Map<Integer, String> map2 = new HashMap<>((int) Math.ceil(4 / (double) 0.75)); map2.put(1, "1"); map2.put(2, "2"); map2.put(3, "3"); // capacity: 6 map2.put(4, "4"); // capacity: 6 // JDK 19 // Analog methods exists for HashSet, LinkedHashSet, LinkedHashMap and WeakHashMap Map<Integer, String> map3 = HashMap.newHashMap(4); map3.put(1, "1"); map3.put(2, "2"); map3.put(3, "3"); // capacity: 6 map3.put(4, "4"); // capacity: 6 } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P123_TheBinomialHeapDS/src/main/java/modern/challenge/BinomialHeap.java
Chapter05/P123_TheBinomialHeapDS/src/main/java/modern/challenge/BinomialHeap.java
package modern.challenge; import java.util.ArrayList; import java.util.List; public class BinomialHeap { private Node head; private final class Node { private int key; private int degree; private Node parent; private Node child; private Node sibling; public Node() { key = Integer.MIN_VALUE; } public Node(int key) { this.key = key; } private void print(StringBuilder sb) { Node currentNode = this; while (currentNode != null) { if (currentNode.key != Integer.MIN_VALUE) { sb.append(" "); sb.append(currentNode.key); sb.append(" "); } if (currentNode.child != null) { sb.append("[ "); currentNode.child.print(sb); sb.append(" ]"); } currentNode = currentNode.sibling; } } } public BinomialHeap() { head = null; } private BinomialHeap(Node head) { this.head = head; } public void insert(int key) { Node node = new Node(key); BinomialHeap newHeap = new BinomialHeap(node); head = unionHeap(newHeap); } public int findMin() { if (head == null) { return Integer.MIN_VALUE; } else { Node min = head; Node nextNode = min.sibling; while (nextNode != null) { if (nextNode.key < min.key) { min = nextNode; } nextNode = nextNode.sibling; } return min.key; } } public void decreaseKey(int key, int newKey) { Node found = findByKey(key); if (found != null) { decreaseKey(found, newKey); } } private void decreaseKey(Node node, int newKey) { node.key = newKey; goUp(node, false); } public void delete(int key) { Node found = findByKey(key); if (found != null) { delete(found); } } private void delete(Node node) { node = goUp(node, true); if (head == node) { deleteTreeRoot(node, null); } else { Node previousNode = head; while (previousNode.sibling.key != node.key) { previousNode = previousNode.sibling; } deleteTreeRoot(node, previousNode); } } private Node goUp(Node node, boolean goToRoot) { Node parent = node.parent; while (parent != null && (goToRoot || node.key < parent.key)) { int t = node.key; node.key = parent.key; parent.key = t; node = parent; parent = parent.parent; } return node; } public int extractMin() { if (head == null) { return Integer.MIN_VALUE; } Node min = head; Node minPrev = null; Node nextNode = min.sibling; Node nextNodePrev = min; while (nextNode != null) { if (nextNode.key < min.key) { min = nextNode; minPrev = nextNodePrev; } nextNodePrev = nextNode; nextNode = nextNode.sibling; } deleteTreeRoot(min, minPrev); return min.key; } private void deleteTreeRoot(Node root, Node previousNode) { if (root == head) { head = root.sibling; } else { previousNode.sibling = root.sibling; } Node unionHeap = null; Node child = root.child; while (child != null) { Node nextNode = child.sibling; child.sibling = unionHeap; child.parent = null; unionHeap = child; child = nextNode; } BinomialHeap toUnionHeap = new BinomialHeap(unionHeap); head = unionHeap(toUnionHeap); } private Node findByKey(int key) { List<Node> nodes = new ArrayList<>(); nodes.add(head); while (!nodes.isEmpty()) { Node currentNode = nodes.get(0); nodes.remove(0); if (currentNode.key == key) { return currentNode; } if (currentNode.sibling != null) { nodes.add(currentNode.sibling); } if (currentNode.child != null) { nodes.add(currentNode.child); } } return null; } private void linkNodes(Node minNodeTree, Node other) { other.parent = minNodeTree; other.sibling = minNodeTree.child; minNodeTree.child = other; minNodeTree.degree++; } public BinomialHeap union(BinomialHeap heap) { Node node = unionHeap(heap); BinomialHeap bh = new BinomialHeap(node); return bh; } private Node unionHeap(BinomialHeap heap) { Node mergeHeap = merge(this, heap); head = null; heap.head = null; if (mergeHeap == null) { return null; } Node previousNode = null; Node currentNode = mergeHeap; Node nextNode = mergeHeap.sibling; while (nextNode != null) { if (currentNode.degree != nextNode.degree || (nextNode.sibling != null && nextNode.sibling.degree == currentNode.degree)) { previousNode = currentNode; currentNode = nextNode; } else { if (currentNode.key < nextNode.key) { currentNode.sibling = nextNode.sibling; linkNodes(currentNode, nextNode); } else { if (previousNode == null) { mergeHeap = nextNode; } else { previousNode.sibling = nextNode; } linkNodes(nextNode, currentNode); currentNode = nextNode; } } nextNode = currentNode.sibling; } return mergeHeap; } private Node merge(BinomialHeap h1, BinomialHeap h2) { if (h1.head == null) { return h2.head; } else if (h2.head == null) { return h1.head; } else { Node headIt; Node h1Next = h1.head; Node h2Next = h2.head; if (h1.head.degree <= h2.head.degree) { headIt = h1.head; h1Next = h1Next.sibling; } else { headIt = h2.head; h2Next = h2Next.sibling; } Node tail = headIt; while (h1Next != null && h2Next != null) { if (h1Next.degree <= h2Next.degree) { tail.sibling = h1Next; h1Next = h1Next.sibling; } else { tail.sibling = h2Next; h2Next = h2Next.sibling; } tail = tail.sibling; } if (h1Next != null) { tail.sibling = h1Next; } else { tail.sibling = h2Next; } return headIt; } } public boolean isEmpty() { return head == null; } public void clear() { head = null; } public void print() { StringBuilder sb = new StringBuilder(); if (head != null) { head.print(sb); } System.out.println(sb.toString()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P123_TheBinomialHeapDS/src/main/java/modern/challenge/Main.java
Chapter05/P123_TheBinomialHeapDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { BinomialHeap h1 = new BinomialHeap(); h1.insert(11); h1.insert(8); h1.insert(24); h1.insert(13); h1.insert(22); h1.insert(40); h1.insert(31); System.out.println("H1: "); h1.print(); BinomialHeap h2 = new BinomialHeap(); h2.insert(18); h2.insert(3); h2.insert(37); h2.insert(5); h2.insert(7); h2.insert(9); h2.insert(40); h2.insert(29); h2.insert(24); h2.insert(45); h2.insert(55); System.out.println("H2: "); h2.print(); BinomialHeap h3 = h1.union(h2); System.out.println("H3: "); h3.print(); int extracted = h3.extractMin(); System.out.println("\nExtract min: " + extracted); System.out.println("Heap after extract min: "); h3.print(); h3.delete(31); System.out.println("\nHeap after deleting 31: "); h3.print(); h3.decreaseKey(24, 2); System.out.println("\nHeap after decreasing 24 to 2: "); h3.print(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P118_SequencedCollectionsAddFirstLast/src/main/java/modern/challenge/Main.java
Chapter05/P118_SequencedCollectionsAddFirstLast/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.SequencedMap; import java.util.SequencedSet; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { // ArrayList List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 list.add(0, "zero"); // add on the first position list.add("six"); // add on the last position // JDK 21 list.addFirst("zero"); list.addLast("six"); // LinkedList List<String> linkedlist = new LinkedList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 linkedlist.add(0, "zero"); // add on the first position linkedlist.add("six"); // add on the last position // JDK 21 linkedlist.addFirst("zero"); linkedlist.addLast("six"); // LinkedHashSet SequencedSet<String> linkedhashset = new LinkedHashSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 // cannot add on first position linkedhashset.add("six"); // JDK 21 linkedhashset.addFirst("zero"); linkedhashset.addLast("six"); // SortedSet SortedSet<String> sortedset = new TreeSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 sortedset.add("zero"); // this will not be the first element sortedset.add("six"); // this will not be the last element // JDK 21 // sortedset.addFirst("zero"); // throws UnsupportedOperationException. // sortedset.addLast("six"); // throws UnsupportedOperationException. // LinkedHashMap SequencedMap<Integer, String> linkedhashmap = new LinkedHashMap<>(); linkedhashmap.put(1, "one"); linkedhashmap.put(2, "two"); linkedhashmap.put(3, "three"); linkedhashmap.put(4, "four"); linkedhashmap.put(5, "five"); // before JDK 21 // linkedhashmap.entrySet().add(new SimpleEntry<>(0, "zero")); // throws UnsupportedOperationException // linkedhashmap.entrySet().add(new SimpleEntry<>(6, "six")); // throws UnsupportedOperationException SequencedMap<Integer, String> slinkedhashmap = new LinkedHashMap<>(); slinkedhashmap.put(0, "zero"); // add the first entry slinkedhashmap.putAll(linkedhashmap); slinkedhashmap.put(6, "six"); // add the last entry // JDK 21 linkedhashmap.putFirst(0, "zero"); linkedhashmap.putLast(6, "six"); // SortedMap SortedMap<Integer, String> sortedmap = new TreeMap<>(); sortedmap.put(1, "one"); sortedmap.put(2, "two"); sortedmap.put(3, "three"); sortedmap.put(4, "four"); sortedmap.put(5, "five"); // before JDK 21 // nothing to do // JDK 21 // sortedmap.putFirst(0, "zero"); // throws UnsupportedOperationException // sortedmap.putLast(6, "six"); // throws UnsupportedOperationException } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P129_TheUnrolledLinkedListDS_2/src/main/java/modern/challenge/UnrolledLinkedList.java
Chapter05/P129_TheUnrolledLinkedListDS_2/src/main/java/modern/challenge/UnrolledLinkedList.java
package modern.challenge; class UnrolledLinkedList { private final int ns; private Node start; private Node end; private int size; private final class Node { private final int arr[]; private Node next; private int items; public Node(int ns) { arr = new int[ns]; } } public UnrolledLinkedList(int capacity) { ns = capacity + 1; } public void insert(int a) { size++; if (start == null) { start = new Node(ns); start.arr[0] = a; start.items++; end = start; return; } if (end.items + 1 < ns) { end.arr[end.items] = a; end.items++; } else { Node node = new Node(ns); int j = 0; for (int i = end.items / 2 + 1; i < end.items; i++) { node.arr[j++] = end.arr[i]; } node.arr[j++] = a; node.items = j; end.items = end.items / 2 + 1; end.next = node; end = node; } } /* challenge yourself to implement here deletion based on the description from the book */ public int getSize() { return size; } @Override public String toString() { StringBuilder sb = new StringBuilder("{"); Node node = start; while (node != null) { sb.append("["); for (int i = 0; i < node.items; i++) { sb.append(node.arr[i]).append(" "); } sb.append("], "); node = node.next; } sb.replace(sb.length() - 2, sb.length() - 1, "}"); return sb.toString(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P129_TheUnrolledLinkedListDS_2/src/main/java/modern/challenge/Main.java
Chapter05/P129_TheUnrolledLinkedListDS_2/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { UnrolledLinkedList list = new UnrolledLinkedList(4); list.insert(3); list.insert(4); list.insert(51); list.insert(11); list.insert(12); list.insert(22); list.insert(56); list.insert(6); list.insert(7); list.insert(9); System.out.println("Initial list: " + list.toString()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P125_ThePairingHeapDS/src/main/java/modern/challenge/Main.java
Chapter05/P125_ThePairingHeapDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { PairHeap heap = new PairHeap(); heap.insert(5); heap.insert(1); heap.insert(7); heap.insert(9); System.out.println("Initial heap:"); heap.inOrder(); heap.decreaseKey(9, 2); System.out.println("\nAfter decreasing 9 to 2:"); heap.inOrder(); heap.decreaseKey(5, 4); System.out.println("\nAfter decreasing 5 to 4:"); heap.inOrder(); int min = heap.findMin(); System.out.println("\nMin: " + min); int del = heap.extractMin(); System.out.println("\nDeleted: " + del); System.out.println("\nNew min: " + heap.findMin()); System.out.println("\nAfter deletion:"); heap.inOrder(); boolean is4 = heap.isKey(4); System.out.println("\nIs 4: " + is4); System.out.println("\nEmpty (before call doEmpty()): " + heap.isEmpty()); System.out.println("\nSize (before call doEmpty()): " + heap.size()); heap.doEmpty(); System.out.println("\nEmpty (after call doEmpty()): " + heap.isEmpty()); System.out.println("\nSize (after call doEmpty()): " + heap.size()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P125_ThePairingHeapDS/src/main/java/modern/challenge/PairHeap.java
Chapter05/P125_ThePairingHeapDS/src/main/java/modern/challenge/PairHeap.java
package modern.challenge; public class PairHeap { private Node root; private Node[] tree = new Node[5]; private int size; private final class Node { private int key; private Node leftChild; private Node nextSibling; private Node prev; public Node(int key) { this.key = key; } } public void insert(int key) { Node newNode = new Node(key); if (root == null) { root = newNode; } else { root = compareAndLink(root, newNode); } size++; } private Node compareAndLink(Node xNode, Node yNode) { if (yNode == null) { return xNode; } if (xNode == null) { return yNode; } if (yNode.key < xNode.key) { yNode.prev = xNode.prev; xNode.prev = yNode; xNode.nextSibling = yNode.leftChild; if (xNode.nextSibling != null) { xNode.nextSibling.prev = xNode; } yNode.leftChild = xNode; return yNode; } else { yNode.prev = xNode; xNode.nextSibling = yNode.nextSibling; if (xNode.nextSibling != null) { xNode.nextSibling.prev = xNode; } yNode.nextSibling = xNode.leftChild; if (yNode.nextSibling != null) { yNode.nextSibling.prev = yNode; } xNode.leftChild = yNode; return xNode; } } public void decreaseKey(int key, int newKey) { Node found = findByKey(key); if (found.key < newKey) { throw new IllegalArgumentException(); } found.key = newKey; if (found != root) { if (found.nextSibling != null) { found.nextSibling.prev = found.prev; } if (found.prev.leftChild == found) { found.prev.leftChild = found.nextSibling; } else { found.prev.nextSibling = found.nextSibling; } found.nextSibling = null; root = compareAndLink(root, found); } } private Node toFind = null; public boolean isKey(int key) { toFind = null; return findByKey(key, root) != null; } private Node findByKey(int key) { toFind = null; return findByKey(key, root); } private Node findByKey(int key, Node node) { if (toFind != null || node == null) { return toFind; } Node temp = node; do { if (key == temp.key) { toFind = temp; } else { Node tempChild = temp.leftChild; findByKey(key, tempChild); temp = temp.nextSibling; } } while (temp != node && toFind == null); return toFind; } public int extractMin() { if (isEmpty()) { throw new UnsupportedOperationException("Cannot delete because the heap is empty"); } int key = findMin(); root.key = Integer.MIN_VALUE; if (root.leftChild == null) { root = null; } else { root = combineSiblings(root.leftChild); } size--; return key; } private Node combineSiblings(Node nodeSibling) { if (nodeSibling.nextSibling == null) { return nodeSibling; } int numSiblings = 0; for (; nodeSibling != null; numSiblings++) { tree = doubleIfFull(tree, numSiblings); tree[numSiblings] = nodeSibling; nodeSibling.prev.nextSibling = null; nodeSibling = nodeSibling.nextSibling; } tree = doubleIfFull(tree, numSiblings); tree[numSiblings] = null; int i = 0; for (; i + 1 < numSiblings; i += 2) { tree[i] = compareAndLink(tree[i], tree[i + 1]); } int j = i - 2; if (j == numSiblings - 3) { tree[j] = compareAndLink(tree[j], tree[j + 2]); } for (; j >= 2; j -= 2) { tree[j - 2] = compareAndLink(tree[j - 2], tree[j]); } return tree[0]; } private Node[] doubleIfFull(Node[] tree, int index) { if (index == tree.length) { Node[] treeArray = tree; tree = new Node[index * 2]; System.arraycopy(treeArray, 0, tree, 0, index); } return tree; } public int findMin() { return root != null ? root.key : Integer.MIN_VALUE; } /* Challenge yourself to implement the merge operation based on this pseudo-code */ /* function merge(h1, h2) if h1 == Empty return h2 else if h2 == Empty return h1 else if h1.root < h2.root return new Heap(h1.root, h2 :: h1.tree) else return new Heap(h2.root, h1 :: h2.tree) */ public boolean isEmpty() { return root == null || size <= 0; } public int size() { return size; } public void doEmpty() { root = null; size = 0; } public void inOrder() { inOrder(root); System.out.println(); } private void inOrder(Node node) { if (node != null) { inOrder(node.leftChild); System.out.print(node.key + " "); inOrder(node.nextSibling); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P127_TheSplayTreeDS/src/main/java/modern/challenge/SplayTree.java
Chapter05/P127_TheSplayTreeDS/src/main/java/modern/challenge/SplayTree.java
package modern.challenge; import java.util.ArrayDeque; import java.util.Queue; class SplayTree { private Node root; private int count; private final class Node { private Node left; private Node right; private Node parent; private int data; public Node() { this(0, null, null, null); } public Node(int data) { this(data, null, null, null); } public Node(int data, Node left, Node right, Node parent) { this.left = left; this.right = right; this.parent = parent; this.data = data; } } public SplayTree() { root = null; } public void insert(int data) { Node xNode = root; Node yNode = null; while (xNode != null) { yNode = xNode; if (data > yNode.data) { xNode = xNode.right; } else { xNode = xNode.left; } } xNode = new Node(); xNode.data = data; xNode.parent = yNode; if (yNode == null) { root = xNode; } else if (data > yNode.data) { yNode.right = xNode; } else { yNode.left = xNode; } splay(xNode); count++; } public void insertAll(SplayTree other) { insertAll(other.root); } private void insertAll(Node node) { if (node != null) { insertAll(node.left); insert(node.data); insertAll(node.right); } } private void splay(Node node) { while (node.parent != null) { Node parentNode = node.parent; Node grandpaNode = parentNode.parent; if (grandpaNode == null) { if (node == parentNode.left) { leftChildToParent(node, parentNode); } else { rightChildToParent(node, parentNode); } } else { if (node == parentNode.left) { if (parentNode == grandpaNode.left) { leftChildToParent(parentNode, grandpaNode); leftChildToParent(node, parentNode); } else { leftChildToParent(node, node.parent); rightChildToParent(node, node.parent); } } else { if (parentNode == grandpaNode.left) { rightChildToParent(node, node.parent); leftChildToParent(node, node.parent); } else { rightChildToParent(parentNode, grandpaNode); rightChildToParent(node, parentNode); } } } } root = node; } private void leftChildToParent(Node xNode, Node yNode) { if (xNode == null || yNode == null || yNode.left != xNode || xNode.parent != yNode) { throw new IllegalStateException("Something is not working properly while transforming the left child into parent"); } if (yNode.parent != null) { if (yNode == yNode.parent.left) { yNode.parent.left = xNode; } else { yNode.parent.right = xNode; } } if (xNode.right != null) { xNode.right.parent = yNode; } xNode.parent = yNode.parent; yNode.parent = xNode; yNode.left = xNode.right; xNode.right = yNode; } private void rightChildToParent(Node xNode, Node yNode) { if ((xNode == null) || (yNode == null) || (yNode.right != xNode) || (xNode.parent != yNode)) { throw new IllegalStateException("Something is not working properly while transforming the right child into parent"); } if (yNode.parent != null) { if (yNode == yNode.parent.left) { yNode.parent.left = xNode; } else { yNode.parent.right = xNode; } } if (xNode.left != null) { xNode.left.parent = yNode; } xNode.parent = yNode.parent; yNode.parent = xNode; yNode.right = xNode.left; xNode.left = yNode; } public boolean search(int data) { return searchNode(data) != null; } private Node searchNode(int data) { Node previousNode = null; Node rootNode = root; while (rootNode != null) { previousNode = rootNode; if (data > rootNode.data) { rootNode = rootNode.right; } else if (data < rootNode.data) { rootNode = rootNode.left; } else if (data == rootNode.data) { splay(rootNode); return rootNode; } } if (previousNode != null) { splay(previousNode); return null; } return null; } public void delete(int data) { Node node = searchNode(data); delete(node); } private void delete(Node node) { if (node == null) { return; } splay(node); if ((node.left != null) && (node.right != null)) { Node min = node.left; while (min.right != null) { min = min.right; } min.right = node.right; node.right.parent = min; node.left.parent = null; root = node.left; } else if (node.right != null) { node.right.parent = null; root = node.right; } else if (node.left != null) { node.left.parent = null; root = node.left; } else { root = null; } node.parent = null; node.left = null; node.right = null; node = null; count--; } public boolean isEmpty() { return root == null; } public int count() { return count; } public void clear() { root = null; count = 0; } public enum TraversalOrder { PRE, IN, POST, LEVEL } public void print(TraversalOrder to) { if (isEmpty()) { System.out.println("empty"); return; } switch (to) { // DFS case IN -> printInOrder(root); case PRE -> printPreOrder(root); case POST -> printPostOrder(root); // BFS case LEVEL -> printLevelOrder(root); } } private void printInOrder(Node node) { if (node != null) { printInOrder(node.left); System.out.print(" " + node.data); printInOrder(node.right); } } private void printPreOrder(Node node) { if (node != null) { System.out.print(" " + node.data); printPreOrder(node.left); printPreOrder(node.right); } } private void printPostOrder(Node node) { if (node != null) { printPostOrder(node.left); printPostOrder(node.right); System.out.print(" " + node.data); } } private void printLevelOrder(Node node) { Queue<Node> queue = new ArrayDeque<>(); queue.add(node); while (!queue.isEmpty()) { Node current = queue.poll(); System.out.print(" " + current.data); if (current.left != null) { queue.add(current.left); } if (current.right != null) { queue.add(current.right); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P127_TheSplayTreeDS/src/main/java/modern/challenge/Main.java
Chapter05/P127_TheSplayTreeDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { SplayTree st = new SplayTree(); st.insert(12); st.insert(5); st.insert(123); st.insert(1); st.insert(122); st.insert(10); st.insert(90); st.insert(92); st.print(SplayTree.TraversalOrder.LEVEL); System.out.println("\nFound 5: " + st.search(5)); st.print(SplayTree.TraversalOrder.LEVEL); System.out.println("\nFound 90: " + st.search(90)); st.print(SplayTree.TraversalOrder.LEVEL); System.out.println("\nDeleting 10 ..."); st.delete(10); st.print(SplayTree.TraversalOrder.LEVEL); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P119_TheRopeDS/src/main/java/modern/challenge/Rope.java
Chapter05/P119_TheRopeDS/src/main/java/modern/challenge/Rope.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Objects; public class Rope { public static char indexAt(Node node, int index) { if (node == null) { throw new IllegalArgumentException("The given node cannot be null"); } int len = getLength(node) - 1; if (index < 0 || index > len) { throw new IndexOutOfBoundsException("The given index cannot be negative or greater than " + len); } if (index > node.weight - 1) { return indexAt(node.right, index - node.weight); } else if (node.left != null) { return indexAt(node.left, index); } else { return node.str.charAt(index); } } private static int getLength(Node node) { if (node.str != null) { return node.weight; } else { return getLength(node.left) + (node.right == null ? 0 : getLength(node.right)); } } public static Node concat(Node node1, Node node2) { if (node1 == null || node2 == null) { throw new IllegalArgumentException("The given nodes cannot be null"); } return new Node(node1, node2, getLength(node1)); } public static List<Node> split(Node node, int index) { if (node == null) { throw new IllegalArgumentException("The given node cannot be null"); } int len = getLength(node) - 1; if (index < 0 || index > len) { throw new IndexOutOfBoundsException("The given index cannot be negative or greater than " + len); } List<Node> ropesInit = new ArrayList<>(); ropesInit.add(node); int position = index; while (true) { Node previous = ropesInit.get(ropesInit.size() - 1); if (previous == null) { return Arrays.asList(node); } if (position > previous.weight - 1) { position = position - previous.weight; ropesInit.add(previous.right); } else if (previous.left != null) { ropesInit.add(previous.left); } else { break; } } if (position > 0) { Node parentNode = ropesInit.get(ropesInit.size() - 1); Node nodeLeft = new Node(parentNode.str.substring(0, position)); Node nodeRight = new Node(parentNode.str.substring(position)); parentNode.str = null; parentNode.weight = position; parentNode.left = nodeLeft; parentNode.right = nodeRight; ropesInit.add(nodeRight); } List<Node> ropesConcat = new ArrayList<>(); boolean goback = false; Node previousNode = ropesInit.get(ropesInit.size() - 1); while (!ropesInit.isEmpty()) { Node nextNode = ropesInit.remove(ropesInit.size() - 1); Node cutNode = null; if (goback) { if (nextNode.left == previousNode && nextNode.right != null) { cutNode = nextNode.right; } } else if (nextNode.right == previousNode) { cutNode = previousNode; goback = true; } previousNode = nextNode; if (cutNode != null) { ropesConcat.add(cutNode); nextNode.right = null; for (int i = ropesInit.size() - 1; i >= 0; i--) { if (ropesInit.get(i).left == nextNode) { ropesInit.get(i).weight -= cutNode.weight; } nextNode = ropesInit.get(i); } } } List<Node> ropesResult = new ArrayList<>(); ropesResult.add(node); Iterator<Node> iterator = ropesConcat.iterator(); if (iterator.hasNext()) { Node concat = iterator.next(); while (iterator.hasNext()) { concat = Rope.concat(concat, iterator.next()); } ropesResult.add(concat); } return ropesResult; } public static Node insert(Node node, int index, String str) { if (node == null) { throw new IllegalArgumentException("The given node cannot be null"); } if (str == null || str.length() == 0) { throw new IllegalArgumentException("The given string cannot be null or empty"); } int len = getLength(node) - 1; if (index < 0 || index > len) { throw new IndexOutOfBoundsException("The given index cannot be negative or greater than " + len); } List<Node> splitRopes = Rope.split(node, index); Node insertNode = new Node(null, null, str.length(), str); Node resultNode; if (splitRopes.size() == 1) { if (index == 0) { resultNode = Rope.concat(insertNode, splitRopes.get(0)); } else { resultNode = Rope.concat(splitRopes.get(0), insertNode); } } else { resultNode = Rope.concat(splitRopes.get(0), insertNode); resultNode = Rope.concat(resultNode, splitRopes.get(1)); } return resultNode; } public static Node delete(Node node, int start, int end) { if (node == null) { throw new IllegalArgumentException("The given node cannot be null"); } int len = getLength(node) - 1; if (start < 0 || start > len) { throw new IndexOutOfBoundsException("The given start cannot be negative or greater than " + len); } if (end < 0 || end > len) { throw new IndexOutOfBoundsException("The end index cannot be negative or greater than " + len); } if (start >= end) { throw new IndexOutOfBoundsException("The given start cannot >= than the given end"); } Node beforeNode = null; Node afterNode; List<Node> splitRopes1 = Rope.split(node, start); if (splitRopes1.size() == 1) { afterNode = splitRopes1.get(0); } else { beforeNode = splitRopes1.get(0); afterNode = splitRopes1.get(1); } List<Node> splitRopes2 = Rope.split(afterNode, end - start); if (splitRopes2.size() == 1) { return beforeNode; } return beforeNode == null ? splitRopes2.get(1) : Rope.concat(beforeNode, splitRopes2.get(1)); } public static class Node { private Node left; private Node right; private int weight; private String str; public Node(String str) { this(null, null, str.length(), str); } public Node(Node left, Node right, int weight) { this(left, right, weight, null); } public Node(Node left, Node right, int weight, String str) { this.left = left; this.right = right; this.str = str; this.weight = weight; } public String buildStr() { StringBuilder treeString = new StringBuilder(); buildStr(this, treeString); return treeString.toString(); } private static void buildStr(Node node, StringBuilder treeString) { if (node.str != null) { treeString.append(node.str); } else { buildStr(node.left, treeString); if (node.right != null) { buildStr(node.right, treeString); } } } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof Node that) { return Objects.equals(str, that.str) && Objects.equals(left, that.left) && Objects .equals(right, that.right) && Objects.equals(weight, that.weight); } return super.equals(obj); } @Override public int hashCode() { return Objects.hash(left, right, weight, str); } @Override public String toString() { StringBuilder treeString = new StringBuilder(); treeRope(this, treeString, 0); return treeString.toString(); } private static void treeRope(Node node, StringBuilder treeString, int deep) { if (node == null) { treeString.append("null"); return; } String padding = " ".repeat(deep); treeString.append("{\n"); treeString.append(padding).append(" weight: ").append(node.weight).append(", \n"); treeString.append(padding).append(" left: "); treeRope(node.left, treeString, deep + 1); treeString.append(", \n"); treeString.append(padding).append(" right: "); treeRope(node.right, treeString, deep + 1); treeString.append(", \n"); treeString.append(padding).append(" str: ").append(node.str); } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P119_TheRopeDS/src/main/java/modern/challenge/Main.java
Chapter05/P119_TheRopeDS/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.List; public class Main { public static void main(String[] args) { Rope.Node I = new Rope.Node("I"); Rope.Node am = new Rope.Node("am"); Rope.Node a = new Rope.Node("a"); Rope.Node very = new Rope.Node("very"); Rope.Node cool = new Rope.Node("cool"); Rope.Node rope = new Rope.Node("rope"); Rope.Node Iam = Rope.concat(I, am); Rope.Node avery = Rope.concat(a, very); Rope.Node coolrope = Rope.concat(cool, rope); Rope.Node Iamavery = Rope.concat(Iam, avery); Rope.Node Iamaverycoolrope = Rope.concat(Iamavery, coolrope); // print the rope as a string System.out.println("Print the rope as a string:"); System.out.println("------------------------------------------------\n"); System.out.println(Iamaverycoolrope.buildStr()); System.out.println(); // print the rope as a tree System.out.println("Print the rope as a tree:"); System.out.println("------------------------------------------------\n"); System.out.println(Iamaverycoolrope); // call toString() System.out.println(); // get character at index 5 System.out.println("Get character at index 5:"); System.out.println("------------------------------------------------\n"); char fivech = Rope.indexAt(Iamaverycoolrope, 5); System.out.println("Character at position 5: " + fivech); System.out.println(); // insert a new node System.out.println("Insert a node:"); System.out.println("------------------------------------------------\n"); Rope.Node Iamasuperverycoolrope = Rope.insert(Iamaverycoolrope, 8, "super"); System.out.println(Iamasuperverycoolrope.buildStr()); System.out.println(); System.out.println(Iamasuperverycoolrope); System.out.println(); // delete a node System.out.println("Delete a node:"); System.out.println("------------------------------------------------\n"); Iamaverycoolrope = Rope.delete(Iamasuperverycoolrope, 8, 13); System.out.println(Iamaverycoolrope.buildStr()); System.out.println(Iamaverycoolrope); System.out.println(); // split the rope in two ropes System.out.println("Split the rope in two ropes:"); System.out.println("------------------------------------------------\n"); List<Rope.Node> ropes = Rope.split(Iamaverycoolrope, 8); System.out.println(ropes.get(0).buildStr()); System.out.println(ropes.get(1).buildStr()); System.out.println(); System.out.println(ropes.get(0)); System.out.println(); System.out.println(ropes.get(1)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P124_TheFibonacciHeapDS/src/main/java/modern/challenge/FibonacciHeap.java
Chapter05/P124_TheFibonacciHeapDS/src/main/java/modern/challenge/FibonacciHeap.java
package modern.challenge; import java.util.NoSuchElementException; public class FibonacciHeap { private Node min; private int nrOfItems; private final class Node { private Node parent; private Node right; private Node left; private Node child; private int degree; private int key; private boolean mark; private Node(int key) { this.key = key; this.right = this; this.left = this; } private void cut(Node node, Node min) { node.left.right = node.right; node.right.left = node.left; degree--; if (degree == 0) { child = null; } else if (child == node) { child = node.right; } node.right = min; node.left = min.left; min.left = node; node.left.right = node; node.parent = null; node.mark = false; } private void cascadingCut(Node min) { Node parentNode = parent; if (parentNode != null) { if (mark) { parentNode.cut(this, min); parentNode.cascadingCut(min); } else { mark = true; } } } private void link(Node parent) { left.right = right; right.left = left; this.parent = parent; if (parent.child == null) { parent.child = this; right = this; left = this; } else { left = parent.child; right = parent.child.right; parent.child.right = this; right.left = this; } parent.degree++; mark = false; } private void addToString(StringBuilder sb) { Node currentNode = this; do { sb.append(" "); sb.append(currentNode.key); sb.append(" "); if (currentNode.child != null) { sb.append("["); currentNode.child.addToString(sb); sb.append(" ]"); } currentNode = currentNode.right; } while (currentNode != this); } } public void insert(int key) { Node node = new Node(key); if (min != null) { node.right = min; node.left = min.left; min.left = node; node.left.right = node; if (node.key < min.key) { min = node; } } else { min = node; } nrOfItems++; } public int extractMin() { Node mNode = min; if (mNode == null) { return Integer.MIN_VALUE; } if (mNode.child != null) { mNode.child.parent = null; for (Node nNode = mNode.child.right; nNode != mNode.child; nNode = nNode.right) { nNode.parent = null; } Node minLeftNode = min.left; Node mChildLeftNode = mNode.child.left; min.left = mChildLeftNode; mChildLeftNode.right = min; mNode.child.left = minLeftNode; minLeftNode.right = mNode.child; } mNode.left.right = mNode.right; mNode.right.left = mNode.left; if (mNode == mNode.right) { min = null; } else { min = mNode.right; consolidate(); } nrOfItems--; return mNode.key; } private void consolidate() { // this is equal to 45 so it can be replaced with a constant double phi = (1 + Math.sqrt(5)) / 2; int fn = (int) (Math.log(Integer.MAX_VALUE) / Math.log(phi)) + 1; Node[] aux = new Node[fn]; Node startNode = min; Node wNode = min; do { Node xNode = wNode; Node nextWNode = wNode.right; int degree = xNode.degree; while (aux[degree] != null) { Node yNode = aux[degree]; if (xNode.key > yNode.key) { Node tempNode = yNode; yNode = xNode; xNode = tempNode; } if (yNode == startNode) { startNode = startNode.right; } if (yNode == nextWNode) { nextWNode = nextWNode.right; } yNode.link(xNode); aux[degree] = null; degree++; } aux[degree] = xNode; wNode = nextWNode; } while (wNode != startNode); min = startNode; for (Node node : aux) { if (node != null && node.key < min.key) { min = node; } } } public void decreaseKey(int key, int newKey) { Node found = findByKey(key); if (found == null) { throw new NoSuchElementException("There is no node with the given key"); } decreaseKey(found, newKey); } private void decreaseKey(Node node, int newKey) { decreaseKey(node, newKey, false); } private void decreaseKey(Node node, int newKey, boolean delete) { node.key = newKey; Node parentNode = node.parent; if (parentNode != null && (delete || node.key < parentNode.key)) { parentNode.cut(node, min); parentNode.cascadingCut(min); } if (delete || node.key < min.key) { min = node; } } public void delete(int key) { Node found = findByKey(key); if (found == null) { throw new NoSuchElementException("There is no node with the given key: " + key); } decreaseKey(found, Integer.MIN_VALUE, true); extractMin(); } private Node toFind = null; public boolean isKey(int key) { toFind = null; return findByKey(key, this.min) != null; } private Node findByKey(int key) { toFind = null; return findByKey(key, this.min); } private Node findByKey(int key, Node node) { if (toFind != null || node == null) { return toFind; } Node temp = node; do { if (key == temp.key) { toFind = temp; } else { Node tempChild = temp.child; findByKey(key, tempChild); temp = temp.right; } } while (temp != node && toFind == null); return toFind; } public boolean isEmpty() { return min == null; } public int min() { return min == null ? Integer.MIN_VALUE : min.key; } public int size() { return nrOfItems; } public void clear() { min = null; nrOfItems = 0; } public static FibonacciHeap merge(FibonacciHeap heap1, FibonacciHeap heap2) { FibonacciHeap heap = new FibonacciHeap(); if (heap1 != null && heap2 != null) { heap.min = heap1.min; if (heap.min != null) { if (heap2.min != null) { heap.min.right.left = heap2.min.left; heap2.min.left.right = heap.min.right; heap.min.right = heap2.min; heap2.min.left = heap.min; if (heap2.min.key < heap1.min.key) { heap.min = heap2.min; } } } else { heap.min = heap2.min; } heap.nrOfItems = heap1.nrOfItems + heap2.nrOfItems; } return heap; } public String heapString() { StringBuilder sb = new StringBuilder(); if (min != null) { sb.append("{"); min.addToString(sb); sb.append("}"); } return sb.toString(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P124_TheFibonacciHeapDS/src/main/java/modern/challenge/Main.java
Chapter05/P124_TheFibonacciHeapDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { FibonacciHeap heap = new FibonacciHeap(); heap.insert(5); heap.insert(1); heap.insert(8); heap.insert(3); heap.insert(9); heap.insert(0); heap.insert(2); heap.insert(7); heap.insert(6); heap.insert(4); System.out.println("Initial heap: \n" + heap.heapString()); heap.extractMin(); System.out.println("Heap after extracting min (aka 0): \n" + heap.heapString()); heap.decreaseKey(8, 0); System.out.println("Heap after decreasing key 8 to 0: \n" + heap.heapString()); heap.delete(3); heap.delete(7); System.out.println("Heap after deleting the 3 and 7 keys: \n" + heap.heapString()); heap.extractMin(); System.out.println("Heap after extracting min (aka 0): \n" + heap.heapString()); heap.insert(7); System.out.println("Heap after inserting the key 7: \n" + heap.heapString()); System.out.println("\nCreating another heap ...\n"); FibonacciHeap heapAux = new FibonacciHeap(); heapAux.insert(15); heapAux.insert(11); heapAux.insert(18); heapAux.insert(13); heapAux.insert(19); System.out.println("Second initial heap: \n" + heapAux.heapString()); heapAux.extractMin(); System.out.println("Second heap after extracting min (aka 11): \n" + heapAux.heapString()); heapAux.decreaseKey(18, 12); System.out.println("Heap after decreasing key 18 to 12: \n" + heapAux.heapString()); FibonacciHeap heapResult = FibonacciHeap.merge(heap, heapAux); System.out.println("Third heap after merging 'heap' and 'heapAux': \n" + heapResult.heapString()); System.out.println("\nThird heap status: \n"); System.out.println("Min: " + heapResult.min()); System.out.println("Empty: " + heapResult.isEmpty()); System.out.println("Size: " + heapResult.size()); heapResult.extractMin(); System.out.println("\nThird heap after extracting min (aka 1): \n" + heapResult.heapString()); boolean is100 = heapResult.isKey(100); boolean is12 = heapResult.isKey(12); System.out.println("\nThird heap contains the key 100: " + is100); System.out.println("\nThird heap contains the key 12: " + is12); heapResult.clear(); System.out.println("\nThird heap after clear: \n" + heapResult.heapString()); System.out.println("\nThird heap status: \n"); System.out.println("Min: " + heapResult.min()); System.out.println("Empty: " + heapResult.isEmpty()); System.out.println("Size: " + heapResult.size()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P118_SequencedCollectionsReverse/src/main/java/modern/challenge/Main.java
Chapter05/P118_SequencedCollectionsReverse/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.NavigableMap; import java.util.SequencedMap; import java.util.SequencedSet; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; @SuppressWarnings("unchecked") public class Main { public static void main(String[] args) { // ArrayList List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 Collections.reverse(list); // reverse the list itself // JDK 21 List<String> reversedList = list.reversed(); // return the reversed view as a new list // LinkedList List<String> linkedlist = new LinkedList<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 Collections.reverse(linkedlist); // reverse the list itself // JDK 21 List<String> reversedLinkedList = linkedlist.reversed(); // return the reversed view as a new linked list // LinkedHashSet SequencedSet<String> linkedhashset = new LinkedHashSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 // nothing to do, just to convert it to an array/arraylist and reverse that // JDK 21 SequencedSet<String> reversedLhs = linkedhashset.reversed(); // SortedSet SortedSet<String> sortedset = new TreeSet<>(Arrays.asList("one", "two", "three", "four", "five")); // before JDK 21 SortedSet<String> reversedSortedSet = new TreeSet<>(sortedset).descendingSet(); // descendingIterator() // JDK 21 SortedSet<String> reversedSortedSetJdk21 = sortedset.reversed(); // LinkedHashMap SequencedMap<Integer, String> linkedhashmap = new LinkedHashMap<>(); linkedhashmap.put(1, "one"); linkedhashmap.put(2, "two"); linkedhashmap.put(3, "three"); linkedhashmap.put(4, "four"); linkedhashmap.put(5, "five"); // before JDK 21 SequencedMap<Integer, String> reversedlinkedhashmap = new LinkedHashMap<>(); Set<Integer> setKeys = linkedhashmap.keySet(); LinkedList<Integer> listKeys = new LinkedList<>(setKeys); Iterator<Integer> iterator = listKeys.descendingIterator(); while (iterator.hasNext()) { Integer key = iterator.next(); reversedlinkedhashmap.put(key, linkedhashmap.get(key)); } // JDK 21 SequencedMap<Integer, String> reversedMap = linkedhashmap.reversed(); // SortedMap SortedMap<Integer, String> sortedmap = new TreeMap<>(); sortedmap.put(1, "one"); sortedmap.put(2, "two"); sortedmap.put(3, "three"); sortedmap.put(4, "four"); sortedmap.put(5, "five"); // before JDK 21 NavigableMap<Integer, String> reversednavigablemap = ((TreeMap) sortedmap).descendingMap(); // JDK 21 SortedMap<Integer, String> reversedsortedmap = sortedmap.reversed(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P121_TheKDTreeDS/src/main/java/modern/challenge/KdTree.java
Chapter05/P121_TheKDTreeDS/src/main/java/modern/challenge/KdTree.java
package modern.challenge; import java.util.ArrayDeque; import java.util.Queue; public class KdTree { private Node root; private Node found; private double foundDistance; private int visited; private final class Node { private final double[] coords; private Node left; private Node right; public Node(double[] coords) { this.coords = coords; } double get(int index) { return coords[index]; } double theDistance(Node node) { double distTotal = 0; for (int i = 0; i < coords.length; ++i) { double dist = coords[i] - node.coords[i]; distTotal += dist * dist; } return distTotal; } @Override public String toString() { StringBuilder sb = new StringBuilder("("); for (int i = 0; i < coords.length; ++i) { if (i > 0) { sb.append(", "); } sb.append(coords[i]); } sb.append(')'); return sb.toString(); } } public void insert(double[] coords) { root = insert(root, coords, 0); } private Node insert(Node root, double[] coords, int depth) { if (root == null) { return newNode(coords); } int cd = depth % 2; if (coords[cd] < root.coords[cd]) { root.left = insert(root.left, coords, depth + 1); } else { root.right = insert(root.right, coords, depth + 1); } return root; } public double[] findNearest(double[] coords) { if (root == null) { throw new IllegalStateException("The tree is empty (cannot find the root)"); } Node targetNode = newNode(coords); visited = 0; foundDistance = 0; found = null; nearest(root, targetNode, 0); return found.coords.clone(); } private void nearest(Node root, Node targetNode, int index) { if (root == null) { return; } visited++; double theDistance = root.theDistance(targetNode); if (found == null || theDistance < foundDistance) { foundDistance = theDistance; found = root; } if (foundDistance == 0) { return; } double rootTargetDistance = root.get(index) - targetNode.get(index); index = (index + 1) % 2; nearest(rootTargetDistance > 0 ? root.left : root.right, targetNode, index); if (rootTargetDistance * rootTargetDistance >= foundDistance) { return; } nearest(rootTargetDistance > 0 ? root.right : root.left, targetNode, index); } public double distance() { return Math.sqrt(foundDistance); } public void printLevelOrder() { Queue<Node> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { Node current = queue.poll(); System.out.print(" " + current); if (current.left != null) { queue.add(current.left); } if (current.right != null) { queue.add(current.right); } } } private Node newNode(double[] coords) { return new Node(coords); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P121_TheKDTreeDS/src/main/java/modern/challenge/Main.java
Chapter05/P121_TheKDTreeDS/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Arrays; public class Main { public static void main(String[] args) { double[][] coords = { {3, 5}, {1, 4}, {5, 4}, {2, 3}, {4, 2}, {3, 2}, {5, 2}, {2, 1}, {2, 4}, {2, 5} }; System.out.println(Arrays.toString(coords[0])); KdTree kd = new KdTree(); for (double[] coord : coords) { System.out.println("Insert: " + Arrays.toString(coord)); kd.insert(coord); } System.out.println("\nNearest (4, 4): " + Arrays.toString(kd.findNearest(new double[]{4, 4}))); System.out.println("\nTree (level order):"); kd.printLevelOrder(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P126_TheHuffmanCodingDS/src/main/java/modern/challenge/Huffman.java
Chapter05/P126_TheHuffmanCodingDS/src/main/java/modern/challenge/Huffman.java
package modern.challenge; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.PriorityQueue; public class Huffman { private Node root; private String str; private StringBuilder encodedStr; private StringBuilder decodedStr; private final class Node { private Node left; private Node right; private final Character character; private final Integer frequency; private Node(Character character, Integer frequency) { this.character = character; this.frequency = frequency; } private Node(Character character, Integer frequency, Node left, Node right) { this.character = character; this.frequency = frequency; this.left = left; this.right = right; } } public void tree(String str) { if (str == null || str.isBlank()) { return; } this.str = str; this.root = null; this.encodedStr = null; this.decodedStr = null; Map<Character, Integer> frequency = new HashMap<>(); for (char character : str.toCharArray()) { frequency.put(character, frequency.getOrDefault(character, 0) + 1); } PriorityQueue<Node> queue = new PriorityQueue<>( Comparator.comparingInt(ch -> ch.frequency)); for (Entry<Character, Integer> entry : frequency.entrySet()) { queue.add(new Node(entry.getKey(), entry.getValue())); } while (queue.size() != 1) { Node left = queue.poll(); Node right = queue.poll(); int sum = left.frequency + right.frequency; queue.add(new Node(null, sum, left, right)); } this.root = queue.peek(); } public String encode() { if (this.root == null) { throw new NoSuchElementException("There is no data available"); } Map<Character, String> codes = new HashMap<>(); encode(this.root, "", codes); this.encodedStr = new StringBuilder(); for (char character : this.str.toCharArray()) { this.encodedStr.append(codes.get(character)); System.out.print(codes.get(character) + "(" + character + ") "); } return this.encodedStr.toString(); } private void encode(Node root, String str, Map<Character, String> codes) { if (root == null) { return; } if (isLeaf(root)) { codes.put(root.character, str.length() > 0 ? str : "1"); } encode(root.left, str + '0', codes); encode(root.right, str + '1', codes); } public String decode() { if (this.root == null || this.encodedStr == null || this.encodedStr.isEmpty()) { throw new NoSuchElementException("There is no data available"); } this.decodedStr = new StringBuilder(); if (isLeaf(this.root)) { int copyFrequency = this.root.frequency; while (copyFrequency-- > 0) { decodedStr.append(root.character); } } else { int index = -1; while (index < this.encodedStr.length() - 1) { index = decode(this.root, index); } } return decodedStr.toString(); } private int decode(Node root, int index) { if (root == null) { return index; } if (isLeaf(root)) { decodedStr.append(root.character); return index; } index++; root = (this.encodedStr.charAt(index) == '0') ? root.left : root.right; index = decode(root, index); return index; } private boolean isLeaf(Node root) { return root.left == null && root.right == null; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P126_TheHuffmanCodingDS/src/main/java/modern/challenge/Main.java
Chapter05/P126_TheHuffmanCodingDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { String dummyText = "aaaaaaaaaaa"; Huffman huffman = new Huffman(); huffman.tree(dummyText); System.out.println("\nEncoded: " + huffman.encode()); System.out.println("Decoded: " + huffman.decode()); System.out.println(); String text = "datastructures"; huffman.tree(text); System.out.println("\nEncoded:" + huffman.encode()); System.out.println("Decoded: " + huffman.decode()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P113_MultiplyingMatricesVectorApi/src/main/java/module-info.java
Chapter05/P113_MultiplyingMatricesVectorApi/src/main/java/module-info.java
module P113_MultiplyingMatricesVectorApi { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P113_MultiplyingMatricesVectorApi/src/main/java/modern/challenge/Main.java
Chapter05/P113_MultiplyingMatricesVectorApi/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Arrays; import java.util.concurrent.ThreadLocalRandom; import jdk.incubator.vector.FloatVector; import jdk.incubator.vector.VectorSpecies; public class Main { private static final VectorSpecies<Float> VS = FloatVector.SPECIES_PREFERRED; public static float[] mulMatrix(float[] x, float[] y, int size) { final int upperBound = VS.loopBound(size); float[] z = new float[size * size]; for (int i = 0; i < size; i++) { for (int k = 0; k < size; k++) { float elem = x[i * size + k]; FloatVector eVector = FloatVector.broadcast(VS, elem); for (int j = 0; j < upperBound; j += VS.length()) { FloatVector yVector = FloatVector.fromArray(VS, y, k * size + j); FloatVector zVector = FloatVector.fromArray(VS, z, i * size + j); zVector = eVector.fma(yVector, zVector); zVector.intoArray(z, i * size + j); } } } return z; } private static final VectorSpecies<Float> VS_512 = FloatVector.SPECIES_512; public static float[] mulMatrixAVX512(float[] x, float[] y, int size) { float[] z = new float[size * size]; final int blockWidth = size >= 256 ? 512 : 256; final int blockHeight = size >= 512 ? 8 : size >= 256 ? 16 : 32; for (int rowOffset = 0; rowOffset < size; rowOffset += blockHeight) { for (int columnOffset = 0; columnOffset < size; columnOffset += blockWidth) { for (int i = 0; i < size; i++) { for (int j = columnOffset; j < columnOffset + blockWidth && j < size; j += VS_512.length()) { FloatVector sum = FloatVector.fromArray(VS_512, z, i * size + j); for (int k = rowOffset; k < rowOffset + blockHeight && k < size; k++) { FloatVector multiplier = FloatVector.broadcast(VS_512, x[i * size + k]); sum = multiplier.fma(FloatVector.fromArray(VS_512, y, k * size + j), sum); } sum.intoArray(z, i * size + j); } } } } return z; } public static void main(String[] args) { // EXAMPLE 1 // | 1 2 5 4 | | 3 4 1 8 | | 62 74 82 69 | // | 5 4 3 7 | | 7 4 9 9 | | 93 110 111 134 | // x * y = z, | 2 2 6 2 | * | 5 6 7 3 | = | 60 68 76 66 | // | 4 1 2 5 | | 5 8 7 7 | | 54 72 62 82 | float[] x = new float[]{1, 2, 5, 4, 5, 4, 3, 7, 2, 2, 6, 2, 4, 1, 2, 5}; float[] y = new float[]{3, 4, 1, 8, 7, 4, 9, 9, 5, 6, 7, 3, 5, 8, 7, 7}; float[] z = mulMatrix(x, y, 4); System.out.println(Arrays.toString(z)); // EXAMPLE 2 System.out.println("\nPlease, be patient, this will take a while ..."); float[] x65536 = new float[256 * 256]; float[] y65536 = new float[256 * 256]; for (int i = 0; i < 256 * 256; i++) { x65536[i] = ThreadLocalRandom.current().nextFloat(); y65536[i] = ThreadLocalRandom.current().nextFloat(); } float[] z65536 = mulMatrixAVX512(x65536, y65536, 256); System.out.println(Arrays.toString(z65536)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Book.java
Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Book.java
package modern.challenge; public record Book(int bookId, String title, int authorId) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Joins.java
Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Joins.java
package modern.challenge; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; @SuppressWarnings("unchecked") public final class Joins { private Joins() { throw new AssertionError("Cannot be instantiated"); } public static List<ResultRow> nestedLoopJoin( List<Author> authorsTable, List<Book> booksTable) { if (authorsTable == null || booksTable == null) { return Collections.emptyList(); } List<ResultRow> resultSet = new LinkedList(); for (Author author : authorsTable) { for (Book book : booksTable) { if (book.authorId() == author.authorId()) { resultSet.add(new ResultRow( author.authorId(), author.name(), book.title(), book.bookId())); } } } return resultSet; } public static List<ResultRow> hashJoin( List<Author> authorsTable, List<Book> booksTable) { if (authorsTable == null || booksTable == null) { return Collections.emptyList(); } Map<Integer, Author> authorMap = new HashMap<>(); for (Author author : authorsTable) { authorMap.put(author.authorId(), author); } List<ResultRow> resultSet = new LinkedList(); for (Book book : booksTable) { Integer authorId = book.authorId(); Author author = authorMap.get(authorId); if (author != null) { resultSet.add(new ResultRow( author.authorId(), author.name(), book.title(), book.bookId())); } } return resultSet; } public static List<ResultRow> sortMergeJoin( List<Author> authorsTable, List<Book> booksTable) { if (authorsTable == null || booksTable == null) { return Collections.emptyList(); } authorsTable.sort(Comparator.comparing(Author::authorId)); booksTable.sort((b1, b2) -> { int sortResult = Comparator .comparing(Book::authorId) .compare(b1, b2); return sortResult != 0 ? sortResult : Comparator .comparing(Book::bookId) .compare(b1, b2); }); List<ResultRow> resultSet = new LinkedList(); int authorCount = authorsTable.size(); int bookCount = booksTable.size(); int p = 0; int q = 0; while (p < authorCount && q < bookCount) { Author author = authorsTable.get(p); Book book = booksTable.get(q); if (author.authorId() == book.authorId()) { resultSet.add(new ResultRow( author.authorId(), author.name(), book.title(), book.bookId())); q++; } else { p++; } } return resultSet; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/ResultRow.java
Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/ResultRow.java
package modern.challenge; public record ResultRow(int authorId, String name, String title, int bookId) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Main.java
Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { List<Author> authorsTable = Arrays.asList( new Author(1, "Author_1"), new Author(2, "Author_2"), new Author(3, "Author_3"), new Author(4, "Author_4"), new Author(5, "Author_5") ); List<Book> booksTable = Arrays.asList( new Book(1, "Book_1", 1), new Book(2, "Book_2", 1), new Book(3, "Book_3", 2), new Book(4, "Book_4", 3), new Book(5, "Book_5", 3), new Book(6, "Book_6", 3), new Book(7, "Book_7", 4), new Book(8, "Book_8", 5), new Book(9, "Book_9", 5) ); List<ResultRow> resultNLJ = Joins.nestedLoopJoin(authorsTable, booksTable); System.out.println("Nested Loop Join: " + resultNLJ); System.out.println(); List<ResultRow> resultHJ = Joins.hashJoin(authorsTable, booksTable); System.out.println("Hash Join: " + resultHJ); System.out.println(); List<ResultRow> resultSMJ = Joins.sortMergeJoin(authorsTable, booksTable); System.out.println("Sort Merge Join: " + resultSMJ); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Author.java
Chapter05/P130_TheJoinAlgorithms/src/main/java/modern/challenge/Author.java
package modern.challenge; public record Author(int authorId, String name) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P128_TheIntervalTreeDS/src/main/java/modern/challenge/IntervalTree.java
Chapter05/P128_TheIntervalTreeDS/src/main/java/modern/challenge/IntervalTree.java
package modern.challenge; import java.util.ArrayDeque; import java.util.LinkedList; import java.util.List; import java.util.Queue; public class IntervalTree { private Node root; public static final class Interval { private final int min, max; public Interval(int min, int max) { this.min = min; this.max = max; } private boolean overlaps(Interval thiz) { if (thiz.max < this.min) { return false; } return this.max >= thiz.min; } private int compareTo(Interval thiz) { if (this.min < thiz.min) { return -1; } else if (this.min > thiz.min) { return 1; } else if (this.max < thiz.max) { return -1; } else if (this.max > thiz.max) { return 1; } else { return 0; } } @Override public String toString() { return "[" + min + ", " + max + "]"; } } private final class Node { private final Interval interval; private final Integer maxInterval; private Node left; private Node right; private int size; private int maxSubstree; Node(Interval interval, Integer maxInterval) { this.interval = interval; this.maxInterval = maxInterval; this.size = 1; this.maxSubstree = interval.max; } } public void insert(Interval interval) { root = insert(root, interval); } private Node insert(Node root, Interval interval) { if (root == null) { return new Node(interval, interval.max); } if (interval.min < root.interval.min) { root.left = insert(root.left, interval); } else { root.right = insert(root.right, interval); } if (root.maxSubstree < interval.max) { root.maxSubstree = interval.max; } return root; } public boolean contains(Interval interval) { return (get(root, interval) != null); } public Integer get(Interval interval) { return get(root, interval); } private Integer get(Node node, Interval interval) { if (node == null) { return null; } int result = interval.compareTo(node.interval); if (result < 0) { return get(node.left, interval); } else if (result > 0) { return get(node.right, interval); } else { return node.maxInterval; } } public Integer delete(Interval interval) { Integer maxInterval = get(interval); root = delete(root, interval); return maxInterval; } private Node delete(Node node, Interval interval) { if (node == null) { return null; } int result = interval.compareTo(node.interval); if (result < 0) { node.left = delete(node.left, interval); } else if (result > 0) { node.right = delete(node.right, interval); } else { node = joinLeftRight(node.left, node.right); } fixSizeMax(node); return node; } public Interval search(Interval interval) { return search(root, interval); } private Interval search(Node node, Interval interval) { while (node != null) { if (interval.overlaps(node.interval)) { return node.interval; } else if (node.left == null) { node = node.right; } else if (node.left.maxSubstree < interval.min) { node = node.right; } else { node = node.left; } } return null; } public List<Interval> searchAll(Interval interval) { List<Interval> intervals = new LinkedList<>(); searchAll(root, interval, intervals); return intervals; } private boolean searchAll(Node node, Interval interval, List<Interval> intervals) { boolean search1 = false; boolean search2 = false; boolean search3 = false; if (node == null) { return false; } if (interval.overlaps(node.interval)) { intervals.add(node.interval); search1 = true; } if (node.left != null && node.left.maxSubstree >= interval.min) { search2 = searchAll(node.left, interval, intervals); } if (search2 || node.left == null || node.left.maxSubstree < interval.min) { search3 = searchAll(node.right, interval, intervals); } return search1 || search2 || search3; } public int size() { return size(root); } private int size(Node node) { if (node == null) { return 0; } else { return node.size; } } public int height() { return height(root); } private int height(Node node) { if (node == null) { return 0; } return 1 + Math.max(height(node.left), height(node.right)); } private void fixSizeMax(Node node) { if (node == null) { return; } node.size = size(node.left) + size(node.right) + 1; node.maxSubstree = Math.max(node.interval.max, Math.max(max(node.left), max(node.right))); } private int max(Node node) { if (node == null) { return Integer.MIN_VALUE; } return node.maxSubstree; } private Node joinLeftRight(Node leftNode, Node rightNode) { if (leftNode == null) { return rightNode; } if (rightNode == null) { return leftNode; } if (Math.random() * (size(leftNode) + size(rightNode)) < size(leftNode)) { leftNode.right = joinLeftRight(leftNode.right, rightNode); fixSizeMax(leftNode); return leftNode; } else { rightNode.left = joinLeftRight(leftNode, rightNode.left); fixSizeMax(rightNode); return rightNode; } } public enum TraversalOrder { PRE, IN, POST, LEVEL } public void print(TraversalOrder to) { switch (to) { // DFS case IN -> printInOrder(root); case PRE -> printPreOrder(root); case POST -> printPostOrder(root); // BFS case LEVEL -> printLevelOrder(root); } } private void printInOrder(Node node) { if (node != null) { printInOrder(node.left); System.out.print(" " + node.interval); printInOrder(node.right); } } private void printPreOrder(Node node) { if (node != null) { System.out.print(" " + node.interval); printPreOrder(node.left); printPreOrder(node.right); } } private void printPostOrder(Node node) { if (node != null) { printPostOrder(node.left); printPostOrder(node.right); System.out.print(" " + node.interval); } } private void printLevelOrder(Node node) { Queue<Node> queue = new ArrayDeque<>(); queue.add(node); while (!queue.isEmpty()) { Node current = queue.poll(); System.out.print(" " + current.interval); if (current.left != null) { queue.add(current.left); } if (current.right != null) { queue.add(current.right); } } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P128_TheIntervalTreeDS/src/main/java/modern/challenge/Main.java
Chapter05/P128_TheIntervalTreeDS/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { IntervalTree tree = new IntervalTree(); tree.insert(new IntervalTree.Interval(4, 7)); tree.insert(new IntervalTree.Interval(1, 10)); tree.insert(new IntervalTree.Interval(7, 23)); tree.insert(new IntervalTree.Interval(6, 8)); tree.insert(new IntervalTree.Interval(9, 13)); tree.insert(new IntervalTree.Interval(2, 24)); System.out.println("Initial interval tree: "); tree.print(IntervalTree.TraversalOrder.LEVEL); System.out.println(); System.out.println("\nSearch all intervals that overlaps the [23, 25] interval: "); System.out.println(tree.searchAll(new IntervalTree.Interval(23, 25))); System.out.println("\nDelete the [7, 23] interval: "); tree.delete(new IntervalTree.Interval(7, 23)); tree.print(IntervalTree.TraversalOrder.LEVEL); System.out.println(); System.out.println("\nCheck that interval [11, 13] exists: "); System.out.println(tree.contains(new IntervalTree.Interval(11, 13))); IntervalTree.Interval found = tree.search(new IntervalTree.Interval(23, 25)); System.out.println("\nSearch interval [23, 25]: " + found); System.out.println("\nInterval tree height: " + tree.height()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P129_TheUnrolledLinkedListDS_1/src/main/java/modern/challenge/UnrolledLinkedList.java
Chapter05/P129_TheUnrolledLinkedListDS_1/src/main/java/modern/challenge/UnrolledLinkedList.java
package modern.challenge; import java.util.Arrays; public class UnrolledLinkedList { private Node head; private int size; private final class Node { private Node next; private int[] arr; private Node(Node next, int[] arr) { this.next = next; this.arr = arr; } @Override public String toString() { return Arrays.toString(arr); } } public void insert(int[] arr) { if (arr == null || arr.length == 0) { return; } if (this.head == null) { this.head = new Node(null, arr); } else { Node temp = this.head; while (temp.next != null) { temp = temp.next; } temp.next = new Node(null, arr); } this.size += arr.length; } public int get(int index) { if (index < 0 || index > this.size) { return Integer.MIN_VALUE; } Node temp = this.head; while (index >= temp.arr.length) { index -= temp.arr.length; temp = temp.next; } return temp.arr[index]; } public void delete(int index) { if (index < 0 || index > this.size) { return; } if (index < this.head.arr.length) { int[] arr = this.head.arr; this.head.arr = buildNewArr(arr, index); } else { Node temp = this.head; index -= temp.arr.length; while (index >= temp.next.arr.length) { index -= temp.next.arr.length; temp = temp.next; } if (temp.next.arr.length == 1) { temp.next = temp.next.next; } else { int[] arr = temp.next.arr; temp.next.arr = buildNewArr(arr, index);; } } this.size--; } private int[] buildNewArr(int[] arr, int index) { int[] newArr = new int[arr.length - 1]; int j = 0; for (int i = 0; i < arr.length; i++) { if (i == index) { continue; } newArr[j++] = arr[i]; } return newArr; } public int getSize() { return size; } @Override public String toString() { if (this.head == null) { return "{}"; } StringBuilder sb = new StringBuilder("{"); Node tmp = this.head; while (tmp.next != null) { sb.append(tmp.toString()).append(", "); tmp = tmp.next; } return sb.append(tmp.toString()).append("}").toString(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P129_TheUnrolledLinkedListDS_1/src/main/java/modern/challenge/Main.java
Chapter05/P129_TheUnrolledLinkedListDS_1/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { UnrolledLinkedList list = new UnrolledLinkedList(); list.insert(new int[]{3, 4, 51}); list.insert(new int[]{11, 12, 22, 56}); list.insert(new int[]{6, 7}); list.insert(new int[]{9}); System.out.println("Initial list: " + list.toString()); int val22 = list.get(5); System.out.println("\n Element at index 5: " + val22); list.delete(5); System.out.println("\n After deleting the element at index 5: " + list.toString()); list.delete(8); System.out.println("\n After deleting the element at index 8: " + list.toString()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/Main.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/Main.java
package modern.challenge; import modern.challenge.zipper.Cursor; import modern.challenge.zipper.Zipper; import modern.challenge.tree.Node; public class Main { public static void main(String[] args) { // A // / | \ // B C D--- // / | \ \ \ // E F G H I (I will be inserted) Node tree = new Node("A", new Node("B", new Node("E"), new Node("F"), new Node("G")), new Node("C"), new Node("D", new Node("H"))); Cursor<Node> root = Zipper.createZipper(tree); System.out.println("Print the zip tree"); System.out.println("-------------------------------------------------"); root.childrenIterator().forEachRemaining(System.out::println); System.out.println("\nCurrent node is first: " + root.isFirst()); System.out.println(); System.out.println("Navigating from node A to node G"); System.out.println("-------------------------------------------------"); Cursor<Node> gNode = root.down().down(1).right(); // this should be 'G' System.out.println("Current node: " + gNode.unwrap().getName()); System.out.println("Current node is leaf: " + gNode.isLeaf()); System.out.println(); System.out.println("Insert node I as child of node D and sibling of node H (first, navigate from node G to H):"); System.out.println("-------------------------------------------------"); Cursor<Node> hNode = gNode.up().rightMost().down(); System.out.println("Current node: " + hNode.unwrap().getName()); System.out.println("Current node is leaf: " + hNode.isLeaf()); System.out.println("Insert the I node ..."); Cursor<Node> hNewNode = hNode.insertRight(new Node("I")); hNewNode.up().childrenIterator().forEachRemaining(System.out::println); // now, D should have a two children, H and I System.out.println(); System.out.println("Remove the B node (first, navigate from node H to B):"); System.out.println("-------------------------------------------------"); Cursor<Node> bNode = hNewNode.up().leftMost(); System.out.println("Current node: " + bNode.unwrap().getName()); System.out.println("Current node is leaf: " + bNode.isLeaf()); System.out.println("Current node is first: " + bNode.isFirst()); Cursor<Node> parentNode = bNode.remove(); System.out.println(); System.out.println("Back to tree (changes are reflected in the tree)"); System.out.println("-------------------------------------------------"); Node backToTree = Zipper.unwrapZipper(parentNode); System.out.println(backToTree); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/ZipperRange.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/ZipperRange.java
package modern.challenge.zipper; final class ZipperRange { private final ZipperRange parentRange; private final ZipNode<?> parentZipNode; private final Zippable[] leftSiblings; private final Zippable[] rightSiblings; protected ZipperRange(final ZipNode<?> parentZipNode, final ZipperRange parentRange, final Zippable[] leftSiblings, final Zippable[] rightSiblings) { this.parentZipNode = parentZipNode; this.parentRange = parentRange; this.leftSiblings = (leftSiblings == null) ? new Zippable[0] : leftSiblings; this.rightSiblings = (rightSiblings == null) ? new Zippable[0] : rightSiblings; } protected boolean isFirst() { return leftSiblings.length == 0; // if it is the first node then it has no left siblings } protected boolean isLast() { return rightSiblings.length == 0; // if it is the last node then it has no right siblings } protected boolean isRoot() { return parentZipNode == null; } protected Zippable[] leftSiblings() { return leftSiblings; } protected Zippable[] rightSiblings() { return rightSiblings; } protected ZipperRange getParentRange() { return parentRange; } protected ZipNode<?> getParentZipNode() { return parentZipNode; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/ZipNode.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/ZipNode.java
package modern.challenge.zipper; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; public final class ZipNode<T extends Zippable> implements Zippable { private static final Zippable[] DUMMY = new Zippable[0]; private final T node; // wrap the original tree node private Zippable[] children; // list of children for this node // wrap a ZipNode without children protected ZipNode(final T node) { this(node, DUMMY); } // wrap a ZipNode and its children protected ZipNode(final T node, Zippable[] children) { if (node == null) { throw new IllegalArgumentException("The given node cannot be null"); } if (node instanceof ZipNode<?>) { throw new IllegalArgumentException("The given node is already zipped"); } if (children == null) { children = new Zippable[0]; } this.node = node; this.children = children; } @Override public Collection<? extends Zippable> getChildren() { lazyGetChildren(); return (children != null) ? new LinkedList<>(Arrays.asList(children)) : null; } // return the original node public T unwrap() { return node; } public boolean isLeaf() { lazyGetChildren(); return children == null || children.length == 0; } public boolean hasChildren() { lazyGetChildren(); return children != null && children.length > 0; } protected Zippable[] children() { lazyGetChildren(); return children; } protected ZipNode<T> replaceNode(final T node) { lazyGetChildren(); return new ZipNode<>(node, children); } // lazy initialization of children private void lazyGetChildren() { if (children == DUMMY) { Collection<? extends Zippable> nodeChildren = node.getChildren(); children = (nodeChildren == null) ? null : nodeChildren.toArray(Zippable[]::new); } } @Override public String toString() { return node.toString(); // call the original toString() } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Zipper.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Zipper.java
package modern.challenge.zipper; import java.util.Collection; @SuppressWarnings("unchecked") public final class Zipper { public static <T extends Zippable> Cursor<T> createZipper(final T node) { return new Cursor<>(new ZipNode<>(node), new ZipperRange(null, null, null, null)); // root range } public static <T extends Zippable> T unwrapZipper(final Cursor<T> tree) { return Zipper.<T>unwrapZipper(tree.root().zipNode()); } private static <T extends Zippable> T unwrapZipper(final Zippable node) { if (node instanceof ZipNode<?>) { ZipNode<T> zipNode = (ZipNode<T>) node; T original = zipNode.unwrap(); if (!zipNode.isLeaf()) { Collection<T> children = (Collection<T>) original.getChildren(); original.getChildren().clear(); for (Zippable zipped : zipNode.children()) { children.add((T) unwrapZipper(zipped)); } } return original; } else { return (T) node; } } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Cursor.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Cursor.java
package modern.challenge.zipper; import java.util.Collection; import java.util.Iterator; @SuppressWarnings("unchecked") public final class Cursor<T extends Zippable> { private final ZipNode<T> zipNode; // this is a zip node wrapping your node (original node) private final ZipperRange range; protected Cursor(final ZipNode<T> zipNode, final ZipperRange range) { this.zipNode = zipNode; this.range = range; } public ZipNode<T> zipNode() { return zipNode; } public T unwrap() { return zipNode.unwrap(); } public Iterator<T> childrenIterator() { if (isLeaf()) { throw new UnsupportedOperationException( "This operation is not supported for the leaf nodes"); } final Iterator<? extends Zippable> iterator = zipNode.getChildren().iterator(); return new Iterator<T>() { @Override public T next() { Zippable zipNode = iterator.next(); return (zipNode instanceof ZipNode<?>) ? ((ZipNode<T>) zipNode).unwrap() : (T) zipNode; } @Override public void remove() { throw new UnsupportedOperationException( "This operation is not supported"); } @Override public boolean hasNext() { return iterator.hasNext(); } }; } public boolean hasChildren() { return zipNode.hasChildren(); } public boolean isRoot() { return range.isRoot(); } public boolean isFirst() { return range.isFirst(); } public boolean isLast() { return range.isLast(); } public boolean isEnd() { if (hasChildren() || !isLast()) { return false; } else { Cursor<T> upZipNode = this; while (upZipNode.isLast() && !upZipNode.isRoot()) { upZipNode = upZipNode.up(); } return upZipNode.isRoot(); } } public boolean isLeaf() { return zipNode.isLeaf(); } /* API for navigating the zip-tree */ public Cursor<T> up() { if (isRoot()) { throw new UnsupportedOperationException( "This operation is not supported for the root zip node"); } return new Cursor<>(new ZipNode<>((T) range.getParentZipNode().unwrap(), shallowCopyUp()), range.getParentRange()); } public Cursor<T> down(int index) { if (!hasChildren() || index > zipNode.children().length || index < 0) { throw new UnsupportedOperationException( "This operation is not supported if the zip node doesn't " + "have children or the index is larger than the number of children or less than 0"); } return new Cursor<>(toZipNode(zipNode.children()[index]), shallowCopyDown(index)); } public Cursor<T> down() { return down(0); } public Cursor<T> right() { if (isLast()) { throw new UnsupportedOperationException( "This operation is not supported for the most-right zip node"); } return new Cursor<>(toZipNode(range.rightSiblings()[0]), shallowCopyRight()); } public Cursor<T> left() { if (isFirst()) { throw new UnsupportedOperationException( "This operation is not supported for the most-left zip node"); } int leftlen = range.leftSiblings().length - 1; return new Cursor<>(toZipNode(range.leftSiblings()[leftlen]), shallowCopyLeft(leftlen)); } public Cursor<T> rightMost() { Cursor<T> currentZipNode = this; while (!currentZipNode.isLast()) { currentZipNode = currentZipNode.right(); } return currentZipNode; } public Cursor<T> leftMost() { Cursor<T> currentZipNode = this; while (!currentZipNode.isFirst()) { currentZipNode = currentZipNode.left(); } return currentZipNode; } public Cursor<T> root() { Cursor<T> currentZipNode = this; while (!currentZipNode.isRoot()) { currentZipNode = currentZipNode.up(); } return currentZipNode; } /* API for manipulating the zip-tree */ public Cursor<T> add(final T... zipNodes) { if (isLeaf()) { throw new UnsupportedOperationException("This operation is not supported for leaf nodes"); } if(zipNodes == null || zipNodes.length == 0) { throw new IllegalArgumentException("The given zip nodes cannot be null or empty"); } return new Cursor<>(new ZipNode<>(unwrap(), shallowCopyAdd(zipNodes)), range); } public Cursor<T> addAll(final Collection<T> zipNodes) { return add((T[]) zipNodes.toArray()); } public Cursor<T> clear() { if (isLeaf()) { throw new UnsupportedOperationException( "This operation is not supported for leaf nodes"); } return new Cursor<>(new ZipNode<>(unwrap(), new Zippable[0]), range); } public Cursor<T> insertLeft(T... zipNodes) { if(zipNodes == null || zipNodes.length == 0) { throw new IllegalArgumentException("The given zip nodes cannot be null or empty"); } return new Cursor<>(zipNode, shallowCopyInsertLeft(zipNodes)); } public Cursor<T> insertRight(T... zipNodes) { if(zipNodes == null || zipNodes.length == 0) { throw new IllegalArgumentException("The given zip nodes cannot be null or empty"); } return new Cursor<>(zipNode, shallowCopyInsertRight(zipNodes)); } public Cursor<T> remove() { if (isRoot()) { throw new UnsupportedOperationException( "This operation is not supported for the root node"); } return new Cursor<>(new ZipNode<>((T) range.getParentZipNode().unwrap(), shallowCopyRemove()), range.getParentRange()); } public Cursor<T> removeLeft() { if (isFirst()) { throw new UnsupportedOperationException( "This operation is not supported for the left-most node"); } return new Cursor<>(zipNode, shallowCopyRemoveLeft()); } public Cursor<T> removeRight() { if (isLast()) { throw new UnsupportedOperationException( "This operation is not supported for the right-most node"); } return new Cursor<>(zipNode, shallowCopyRemoveRight()); } public Cursor<T> replace(Zippable node) { if(node == null) { throw new IllegalArgumentException("The given zip node cannot be null"); } return new Cursor<>(toZipNode(node), shallowCopyReplace(range)); } public Cursor<T> replaceOriginal(T node) { if(node == null) { throw new IllegalArgumentException("The given zip node cannot be null"); } if (node instanceof ZipNode<?>) { throw new IllegalArgumentException("Cannot replace an original node with a zip node"); } return new Cursor<>(this.zipNode.replaceNode(node), shallowCopyReplace(range)); } // helper method to get a new zip node private ZipNode<T> toZipNode(final Zippable node) { if (node instanceof ZipNode<?>) { return (ZipNode<T>) node; } else { return new ZipNode<>((T) node); } } // helper method for the up() navigation private Zippable[] shallowCopyUp() { Zippable[] zippable = new Zippable[range.leftSiblings().length + range.rightSiblings().length + 1]; System.arraycopy(range.leftSiblings(), 0, zippable, 0, range.leftSiblings().length); zippable[range.leftSiblings().length] = zipNode; System.arraycopy(range.rightSiblings(), 0, zippable, range.leftSiblings().length + 1, range.rightSiblings().length); return zippable; } // helper method for the down() navigation private ZipperRange shallowCopyDown(int index) { Zippable[] leftSide = new Zippable[index]; System.arraycopy(zipNode.children(), 0, leftSide, 0, leftSide.length); Zippable[] rightSide = new Zippable[zipNode.children().length - index - 1]; System.arraycopy(zipNode.children(), index + 1, rightSide, 0, rightSide.length); return new ZipperRange(zipNode, range, leftSide, rightSide); } // helper method for the right() navigation private ZipperRange shallowCopyRight() { Zippable[] leftSide = new Zippable[range.leftSiblings().length + 1]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length); leftSide[leftSide.length - 1] = zipNode; Zippable[] rightSide = new Zippable[range.rightSiblings().length - 1]; System.arraycopy(range.rightSiblings(), 1, rightSide, 0, range.rightSiblings().length - 1); return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for the left() navigation private ZipperRange shallowCopyLeft(int leftlen) { Zippable[] leftSide = new Zippable[leftlen]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length - 1); Zippable[] rightSide = new Zippable[range.rightSiblings().length + 1]; System.arraycopy(range.rightSiblings(), 0, rightSide, 1, range.rightSiblings().length); rightSide[0] = zipNode; return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for the add() operation private Zippable[] shallowCopyAdd(T... zipNodes) { Zippable[] zippable = new Zippable[zipNodes.length + zipNode.children().length]; System.arraycopy(zipNode.children(), 0, zippable, 0, zipNode.children().length); System.arraycopy(zipNodes, 0, zippable, zipNode.children().length, zipNodes.length); return zippable; } // helper method for insertLeft() operation private ZipperRange shallowCopyInsertLeft(T... zipNodes) { Zippable[] leftSide = new Zippable[range.leftSiblings().length + zipNodes.length]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length); System.arraycopy(zipNodes, 0, leftSide, range.leftSiblings().length, zipNodes.length); Zippable[] rightSide = new Zippable[range.rightSiblings().length]; System.arraycopy(range.rightSiblings(), 0, rightSide, 0, range.rightSiblings().length); return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for insertRight() operation private ZipperRange shallowCopyInsertRight(T... zipNodes) { Zippable[] leftSide = new Zippable[range.leftSiblings().length]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length); Zippable[] rightSide = new Zippable[range.rightSiblings().length + zipNodes.length]; System.arraycopy(zipNodes, 0, rightSide, 0, zipNodes.length); System.arraycopy(range.rightSiblings(), 0, rightSide, zipNodes.length, range.rightSiblings().length); return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for the remove() operation private Zippable[] shallowCopyRemove() { Zippable[] zippable = new Zippable[range.leftSiblings().length + range.rightSiblings().length]; System.arraycopy(range.leftSiblings(), 0, zippable, 0, range.leftSiblings().length); System.arraycopy(range.rightSiblings(), 0, zippable, range.leftSiblings().length, range.rightSiblings().length); return zippable; } // helper method for removeLeft() operation private ZipperRange shallowCopyRemoveLeft() { Zippable[] leftSide = new Zippable[range.leftSiblings().length - 1]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length - 1); Zippable[] rightSide = new Zippable[range.rightSiblings().length]; System.arraycopy(range.rightSiblings(), 0, rightSide, 0, range.rightSiblings().length); return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for removeRight() operation private ZipperRange shallowCopyRemoveRight() { Zippable[] leftSide = new Zippable[range.leftSiblings().length]; System.arraycopy(range.leftSiblings(), 0, leftSide, 0, range.leftSiblings().length); Zippable[] rightSide = new Zippable[range.rightSiblings().length - 1]; System.arraycopy(range.rightSiblings(), 1, rightSide, 0, range.rightSiblings().length - 1); return new ZipperRange(range.getParentZipNode(), range.getParentRange(), leftSide, rightSide); } // helper method for replace() and replaceOriginal() operations private ZipperRange shallowCopyReplace(ZipperRange zipperRange) { Zippable[] leftSide = zipperRange.leftSiblings().clone(); Zippable[] rightSide = zipperRange.rightSiblings().clone(); return new ZipperRange(zipperRange.getParentZipNode(), zipperRange.getParentRange(), leftSide, rightSide); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Zippable.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/zipper/Zippable.java
package modern.challenge.zipper; import java.util.Collection; public interface Zippable { public Collection<? extends Zippable> getChildren(); }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/tree/Node.java
Chapter05/P122_TheZipperDS/src/main/java/modern/challenge/tree/Node.java
package modern.challenge.tree; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import modern.challenge.zipper.Zippable; public class Node implements Zippable { private final String name; private final List<Node> children; public Node(final String name, final Node... children) { if (name == null) { throw new IllegalArgumentException("The given name cannot be null"); } this.name = name; this.children = new LinkedList<>(Arrays.asList(children)); } public String getName() { return name; } @Override public Collection<Node> getChildren() { return this.children; } @Override public String toString() { return "Node{" + "name=" + name + ", children=" + children + '}'; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P109_SimpleSummingArrays/src/main/java/module-info.java
Chapter05/P109_SimpleSummingArrays/src/main/java/module-info.java
module P109_SimpleSummingArrays { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P109_SimpleSummingArrays/src/main/java/modern/challenge/Main.java
Chapter05/P109_SimpleSummingArrays/src/main/java/modern/challenge/Main.java
package modern.challenge; import jdk.incubator.vector.IntVector; public class Main { public static void main(String[] args) { int[] x = new int[]{1, 2, 3, 4, 5, 6, 7, 8}; int[] y = new int[]{4, 5, 2, 5, 1, 3, 8, 7}; IntVector xVector = IntVector.fromArray(IntVector.SPECIES_256, x, 0); IntVector yVector = IntVector.fromArray(IntVector.SPECIES_256, y, 0); IntVector zVector = xVector.add(yVector); System.out.println(zVector); // [5, 7, 5, 9, 6, 9, 15, 15] } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P116_StreamToList/src/main/java/modern/challenge/MelonRecord.java
Chapter05/P116_StreamToList/src/main/java/modern/challenge/MelonRecord.java
package modern.challenge; public record MelonRecord(String type, float weight) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P116_StreamToList/src/main/java/modern/challenge/MelonMarket.java
Chapter05/P116_StreamToList/src/main/java/modern/challenge/MelonMarket.java
package modern.challenge; import java.util.List; public record MelonMarket(List<MelonRecord> melons) {}
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P116_StreamToList/src/main/java/modern/challenge/Main.java
Chapter05/P116_StreamToList/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.File; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Main { public static void main(String[] args) { // JDK 8 List<File> roots8 = Stream.of(File.listRoots()).collect(Collectors.toList()); // JDK 10 List<File> roots10 = Stream.of(File.listRoots()).collect(Collectors.toUnmodifiableList()); // JDK 16 List<File> roots16 = Stream.of(File.listRoots()).toList(); MelonMarket mm1 = new MelonMarket( List.of( new MelonRecord("Gac", 1600), new MelonRecord("Hami", 2000), new MelonRecord("Cantaloupe", 3000) ) ); MelonMarket mm2 = new MelonMarket( List.of( new MelonRecord("Muskmelon", 6000), new MelonRecord("Honeydew", 2000) ) ); List<MelonMarket> mm = List.of(mm1, mm2); // JDK 8 List<MelonRecord> melons8 = mm.stream() .flatMap(m -> m.melons().stream()) .collect(Collectors.toList()); // JDK 10 List<MelonRecord> melons10 = mm.stream() .flatMap(m -> m.melons().stream()) .collect(Collectors.toUnmodifiableList()); // JDK 16 List<MelonRecord> melons16 = mm.stream() .flatMap(m -> m.melons().stream()) .toList(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P110_SummingArraysUnrolled/src/main/java/module-info.java
Chapter05/P110_SummingArraysUnrolled/src/main/java/module-info.java
module P110_SummingArraysUnrolled { requires jdk.incubator.vector; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P110_SummingArraysUnrolled/src/main/java/modern/challenge/Main.java
Chapter05/P110_SummingArraysUnrolled/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Arrays; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorSpecies; public class Main { private static final VectorSpecies<Integer> VS256 = IntVector.SPECIES_256; public static void sumUnrolled(int x[], int y[], int z[]) { int width = VS256.length(); int i = 0; for (; i <= (x.length - width * 4); i += width * 4) { IntVector s1 = IntVector.fromArray(VS256, x, i) .add(IntVector.fromArray(VS256, y, i)); IntVector s2 = IntVector.fromArray(VS256, x, i + width) .add(IntVector.fromArray(VS256, y, i + width)); IntVector s3 = IntVector.fromArray(VS256, x, i + width * 2) .add(IntVector.fromArray(VS256, y, i + width * 2)); IntVector s4 = IntVector.fromArray(VS256, x, i + width * 3) .add(IntVector.fromArray(VS256, y, i + width * 3)); s1.intoArray(z, i); s2.intoArray(z, i + width); s3.intoArray(z, i + width * 2); s4.intoArray(z, i + width * 3); } for (; i < x.length; i++) { z[i] = x[i] + y[i]; } } public static void main(String[] args) { int[] x = new int[]{3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 3, 4}; int[] y = new int[]{4, 5, 2, 5, 1, 3, 8, 7, 1, 6, 2, 3, 1, 2, 3, 4, 5, 6, 7, 8, 3, 6, 5, 5, 1, 2, 3, 4, 5, 6, 7, 8, 2, 8}; int[] z = new int[x.length]; sumUnrolled(x, y, z); System.out.println("Result: " + Arrays.toString(z)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P111_BenchmarkVectors/src/main/java/module-info.java
Chapter05/P111_BenchmarkVectors/src/main/java/module-info.java
module P111_BenchmarkVectors { requires jdk.incubator.vector; requires jmh.generator.annprocess; requires jmh.core; }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter05/P111_BenchmarkVectors/src/main/java/modern/challenge/Main.java
Chapter05/P111_BenchmarkVectors/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.io.IOException; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.TimeUnit; import jdk.incubator.vector.IntVector; import jdk.incubator.vector.VectorMask; import jdk.incubator.vector.VectorSpecies; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; import org.openjdk.jmh.infra.Blackhole; @OutputTimeUnit(TimeUnit.MILLISECONDS) @BenchmarkMode({Mode.AverageTime, Mode.Throughput}) @Warmup(iterations = 3, time = 1) @Measurement(iterations = 5, time = 1) @State(Scope.Benchmark) @Fork(value = 1, warmups = 0, jvmArgsPrepend = {"--add-modules=jdk.incubator.vector"}) public class Main { private static final VectorSpecies<Integer> VS = IntVector.SPECIES_PREFERRED; @Param("50000000") int length; int[] x; int[] y; int[] z; int[] w; int[] k; @Setup public void init() { x = new int[length]; y = new int[length]; z = new int[length]; w = new int[length]; k = new int[length]; for (int i = 0; i < x.length; i++) { x[i] = ThreadLocalRandom.current().nextInt(); y[i] = ThreadLocalRandom.current().nextInt(); z[i] = ThreadLocalRandom.current().nextInt(); } } @Benchmark public void computeWithMask(Blackhole blackhole) { int upperBound = VS.loopBound(x.length); int i = 0; for (; i < upperBound; i += VS.length()) { IntVector xVector = IntVector.fromArray(VS, x, i); IntVector yVector = IntVector.fromArray(VS, y, i); IntVector zVector = xVector.add(yVector); IntVector wVector = xVector.mul(zVector).mul(yVector); IntVector kVector = zVector.add((wVector).mul(yVector)); kVector.intoArray(k, i); } if (i <= (x.length - 1)) { VectorMask<Integer> mask = VS.indexInRange(i, x.length); IntVector xVector = IntVector.fromArray(VS, x, i, mask); IntVector yVector = IntVector.fromArray(VS, y, i, mask); IntVector zVector = xVector.add(yVector); IntVector wVector = xVector.mul(zVector).mul(yVector); IntVector kVector = zVector.add((wVector).mul(yVector)); kVector.intoArray(k, i, mask); } blackhole.consume(k); } @Benchmark public void computeNoMask(Blackhole blackhole) { int upperBound = VS.loopBound(x.length); int i = 0; for (; i < upperBound; i += VS.length()) { IntVector xVector = IntVector.fromArray(VS, x, i); IntVector yVector = IntVector.fromArray(VS, y, i); IntVector zVector = xVector.add(yVector); IntVector wVector = xVector.mul(zVector).mul(yVector); IntVector kVector = zVector.add((wVector).mul(yVector)); kVector.intoArray(k, i); } for (; i < x.length; i++) { z[i] = x[i] + y[i]; w[i] = x[i] * z[i] * y[i]; k[i] = z[i] + w[i] * y[i]; } blackhole.consume(k); } @Benchmark public void computeUnrolledNoMask(Blackhole blackhole) { int width = VS.length(); int i = 0; for (; i <= (x.length - width * 4); i += width * 4) { IntVector zVector1 = IntVector.fromArray(VS, x, i) .add(IntVector.fromArray(VS, y, i)); IntVector zVector2 = IntVector.fromArray(VS, x, i + width) .add(IntVector.fromArray(VS, y, i + width)); IntVector zVector3 = IntVector.fromArray(VS, x, i + width * 2) .add(IntVector.fromArray(VS, y, i + width * 2)); IntVector zVector4 = IntVector.fromArray(VS, x, i + width * 3) .add(IntVector.fromArray(VS, y, i + width * 3)); IntVector wVector1 = IntVector.fromArray(VS, x, i).mul(zVector1).mul(IntVector.fromArray(VS, y, i)); IntVector wVector2 = IntVector.fromArray(VS, x, i + width).mul(zVector2).mul(IntVector.fromArray(VS, y, i + width)); IntVector wVector3 = IntVector.fromArray(VS, x, i + width * 2).mul(zVector3).mul(IntVector.fromArray(VS, y, i + width * 2)); IntVector wVector4 = IntVector.fromArray(VS, x, i + width * 3).mul(zVector4).mul(IntVector.fromArray(VS, y, i + width * 3)); IntVector kVector1 = zVector1.add((wVector1).mul(IntVector.fromArray(VS, y, i))); IntVector kVector2 = zVector2.add((wVector2).mul(IntVector.fromArray(VS, y, i + width))); IntVector kVector3 = zVector3.add((wVector3).mul(IntVector.fromArray(VS, y, i + width * 2))); IntVector kVector4 = zVector4.add((wVector4).mul(IntVector.fromArray(VS, y, i + width * 3))); kVector1.intoArray(k, i); kVector2.intoArray(k, i + width); kVector3.intoArray(k, i + width * 2); kVector4.intoArray(k, i + width * 3); } for (; i < x.length; i++) { z[i] = x[i] + y[i]; w[i] = x[i] * z[i] * y[i]; k[i] = z[i] + w[i] * y[i]; } blackhole.consume(k); } @Benchmark public void computeArrays(Blackhole blackhole) { for (int i = 0; i < x.length; i++) { z[i] = x[i] + y[i]; w[i] = x[i] * z[i] * y[i]; k[i] = z[i] + w[i] * y[i]; } blackhole.consume(k); } public static void main(String[] args) throws IOException { org.openjdk.jmh.Main.main(args); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter12/P255_LoggingGC/src/main/java/modern/challenge/Main.java
Chapter12/P255_LoggingGC/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class Main { private static final Logger logger = Logger.getLogger(Main.class.getName()); private static final List<String> strings = new ArrayList<>(); public static void main(String[] args) { System.setProperty("java.util.logging.SimpleFormatter.format", "[%1$tT] [%4$-7s] %5$s %n"); logger.info("Application started ..."); String string = "prefixedString_"; // Add in heap 5 millions String instances for (int i = 0; i < 5_000_000; i++) { String newString = string + i; strings.add(newString); } logger.info(() -> "List size: " + strings.size()); // Force GC execution System.gc(); // Remove 10_000 out of 5 millions for (int i = 0; i < 10_000; i++) { String newString = string + i; strings.remove(newString); } logger.info(() -> "List size: " + strings.size()); logger.info("Application done ..."); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P69_DateToYearMonth/src/main/java/modern/challenge/DateConverters.java
Chapter03/P69_DateToYearMonth/src/main/java/modern/challenge/DateConverters.java
package modern.challenge; import java.time.YearMonth; import java.time.ZoneId; import java.util.Date; public final class DateConverters { private DateConverters() { throw new AssertionError("Cannot be instantiated"); } public static YearMonth toYearMonth(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } return YearMonth.from(date.toInstant() .atZone(ZoneId.systemDefault()) .toLocalDate()); } public static Date toDate(YearMonth ym) { if (ym == null) { throw new IllegalArgumentException("The given year-month cannot be null"); } return Date.from(ym.atDay(1) .atStartOfDay(ZoneId.systemDefault()).toInstant()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P69_DateToYearMonth/src/main/java/modern/challenge/Main.java
Chapter03/P69_DateToYearMonth/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.text.ParseException; import java.time.YearMonth; import java.util.Date; public class Main { public static void main(String[] args) throws ParseException { System.out.println("Date to YearMonth: " + DateConverters.toYearMonth(new Date())); System.out.println("YearMonth to Date: " + DateConverters.toDate(YearMonth.now())); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P78_FromMidnightToNow/src/main/java/modern/challenge/Main.java
Chapter03/P78_FromMidnightToNow/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; public class Main { public static void main(String[] args) { LocalDateTime now = LocalDateTime.now(); LocalDateTime midnight = LocalDateTime.of(now.getYear(), now.getMonth(), now.getDayOfMonth(), 0, 0, 0); System.out.println("Millis: " + ChronoUnit.MILLIS.between(midnight, now)); System.out.println("Seconds: " + ChronoUnit.SECONDS.between(midnight, now)); System.out.println("Minutes: " + ChronoUnit.MINUTES.between(midnight, now)); System.out.println("Hours: " + ChronoUnit.HOURS.between(midnight, now)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P72_LeapYear/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P72_LeapYear/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.Year; import java.util.Calendar; import java.util.GregorianCalendar; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static boolean isLeapYearV1(int year) { if (year % 4 != 0) { return false; } else if (year % 400 == 0) { return true; } else if (year % 100 == 0) { return false; } return true; } public static boolean isLeapYearV2(int year) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); return calendar.getActualMaximum(Calendar.DAY_OF_YEAR) > 365; } public static boolean isLeapYearV3(int year) { return new GregorianCalendar(year, 1, 1).isLeapYear(year); } public static boolean isLeapYearV4(int year) { return ((year & 3) == 0 && ((year % 25) != 0 || (year & 15) == 0)); } public static boolean isLeapYearV5(int year) { return Year.of(year).isLeap(); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P72_LeapYear/src/main/java/modern/challenge/Main.java
Chapter03/P72_LeapYear/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { System.out.println("-1901: " + DateCheckers.isLeapYearV1(-1901)); System.out.println("-2000: " + DateCheckers.isLeapYearV1(-2000)); System.out.println("0: " + DateCheckers.isLeapYearV1(0)); System.out.println("4: " + DateCheckers.isLeapYearV1(4)); System.out.println("2000: " + DateCheckers.isLeapYearV1(2000)); System.out.println("1904: " + DateCheckers.isLeapYearV1(1904)); System.out.println("1450: " + DateCheckers.isLeapYearV1(1450)); System.out.println("1901: " + DateCheckers.isLeapYearV1(1901)); System.out.println("800: " + DateCheckers.isLeapYearV1(800)); System.out.println("1600: " + DateCheckers.isLeapYearV1(1600)); System.out.println("1900: " + DateCheckers.isLeapYearV1(1900)); System.out.println("2012: " + DateCheckers.isLeapYearV1(2012)); System.out.println("2023: " + DateCheckers.isLeapYearV1(2023)); System.out.println(); System.out.println("-1901: " + DateCheckers.isLeapYearV2(-1901)); System.out.println("-2000: " + DateCheckers.isLeapYearV2(-2000)); System.out.println("0: " + DateCheckers.isLeapYearV2(0)); System.out.println("4: " + DateCheckers.isLeapYearV2(4)); System.out.println("2000: " + DateCheckers.isLeapYearV2(2000)); System.out.println("1904: " + DateCheckers.isLeapYearV2(1904)); System.out.println("1450: " + DateCheckers.isLeapYearV2(1450)); System.out.println("1901: " + DateCheckers.isLeapYearV2(1901)); System.out.println("800: " + DateCheckers.isLeapYearV2(800)); System.out.println("1600: " + DateCheckers.isLeapYearV2(1600)); System.out.println("1900: " + DateCheckers.isLeapYearV2(1900)); System.out.println("2012: " + DateCheckers.isLeapYearV2(2012)); System.out.println("2023: " + DateCheckers.isLeapYearV2(2023)); System.out.println(); System.out.println("-1901: " + DateCheckers.isLeapYearV3(-1901)); System.out.println("-2000: " + DateCheckers.isLeapYearV3(-2000)); System.out.println("0: " + DateCheckers.isLeapYearV3(0)); System.out.println("4: " + DateCheckers.isLeapYearV3(4)); System.out.println("2000: " + DateCheckers.isLeapYearV3(2000)); System.out.println("1904: " + DateCheckers.isLeapYearV3(1904)); System.out.println("1450: " + DateCheckers.isLeapYearV3(1450)); System.out.println("1901: " + DateCheckers.isLeapYearV3(1901)); System.out.println("800: " + DateCheckers.isLeapYearV3(800)); System.out.println("1600: " + DateCheckers.isLeapYearV3(1600)); System.out.println("1900: " + DateCheckers.isLeapYearV3(1900)); System.out.println("2012: " + DateCheckers.isLeapYearV3(2012)); System.out.println("2023: " + DateCheckers.isLeapYearV3(2023)); System.out.println(); System.out.println("-1901: " + DateCheckers.isLeapYearV4(-1901)); System.out.println("-2000: " + DateCheckers.isLeapYearV4(-2000)); System.out.println("0: " + DateCheckers.isLeapYearV4(0)); System.out.println("4: " + DateCheckers.isLeapYearV4(4)); System.out.println("2000: " + DateCheckers.isLeapYearV4(2000)); System.out.println("1904: " + DateCheckers.isLeapYearV4(1904)); System.out.println("1450: " + DateCheckers.isLeapYearV4(1450)); System.out.println("1901: " + DateCheckers.isLeapYearV4(1901)); System.out.println("800: " + DateCheckers.isLeapYearV4(800)); System.out.println("1600: " + DateCheckers.isLeapYearV4(1600)); System.out.println("1900: " + DateCheckers.isLeapYearV4(1900)); System.out.println("2012: " + DateCheckers.isLeapYearV4(2012)); System.out.println("2023: " + DateCheckers.isLeapYearV4(2023)); System.out.println(); System.out.println("-1901: " + DateCheckers.isLeapYearV5(-1901)); System.out.println("-2000: " + DateCheckers.isLeapYearV5(-2000)); System.out.println("0: " + DateCheckers.isLeapYearV5(0)); System.out.println("4: " + DateCheckers.isLeapYearV5(4)); System.out.println("2000: " + DateCheckers.isLeapYearV5(2000)); System.out.println("1904: " + DateCheckers.isLeapYearV5(1904)); System.out.println("1450: " + DateCheckers.isLeapYearV5(1450)); System.out.println("1901: " + DateCheckers.isLeapYearV5(1901)); System.out.println("800: " + DateCheckers.isLeapYearV5(800)); System.out.println("1600: " + DateCheckers.isLeapYearV5(1600)); System.out.println("1900: " + DateCheckers.isLeapYearV5(1900)); System.out.println("2012: " + DateCheckers.isLeapYearV5(2012)); System.out.println("2023: " + DateCheckers.isLeapYearV5(2023)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P75_MonthFromQuarter/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P75_MonthFromQuarter/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.time.Month; import java.util.ArrayList; import java.util.List; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static List<String> quarterMonths(LocalDate ld) { if (ld == null) { throw new IllegalArgumentException("The given date cannot be null"); } List<String> qmonths = new ArrayList<>(); int qmonth = Month.from(ld).firstMonthOfQuarter().getValue(); qmonths.add(Month.of(qmonth).name()); qmonths.add(Month.of(++qmonth).name()); qmonths.add(Month.of(++qmonth).name()); /* int qmonth = Month.from(ld).firstMonthOfQuarter().getValue(); List<String> qmonths = IntStream.of(qmonth, ++qmonth, ++qmonth) .mapToObj(Month::of) .map(Month::name) .collect(Collectors.toList()); */ return qmonths; } public static List<String> quarterMonths(int quarter) { if (quarter < 1 || quarter > 4) { throw new IllegalArgumentException("Quarter can be 1, 2, 3, or 4"); } List<String> qmonths = new ArrayList<>(); int qmonth = quarter * 3 - 2; qmonths.add(Month.of(qmonth).name()); qmonths.add(Month.of(++qmonth).name()); qmonths.add(Month.of(++qmonth).name()); /* int qmonth = quarter * 3 - 2; List<String> qmonths = IntStream.of(qmonth, ++qmonth, ++qmonth) .mapToObj(Month::of) .map(Month::name) .collect(Collectors.toList()); */ return qmonths; } public static List<String> quarterMonths(String quarter) { if (quarter == null) { throw new IllegalArgumentException("Quarter cannot be null"); } if (quarter.isBlank() || quarter.length() != 2) { throw new IllegalArgumentException("Quarter cannot be empty or have the length != 2"); } if (!quarter.matches("^Q([1-4])$")) { throw new IllegalArgumentException("Quarter values are: Q1, Q2, Q3, or Q4"); } List<String> qmonths = new ArrayList<>(); int qmonth = Integer.parseInt(quarter.replaceAll("\\D", "")) * 3 - 2; for (int i = 0; i < 3; i++) { qmonths.add(Month.of(qmonth + i).name()); } /* int qmonth = Integer.parseInt(quarter.replaceAll("\\D", "")) * 3 - 2; List<String> qmonths = IntStream.of(qmonth, ++qmonth, ++qmonth) .mapToObj(Month::of) .map(Month::name) .collect(Collectors.toList()); */ return qmonths; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P75_MonthFromQuarter/src/main/java/modern/challenge/Main.java
Chapter03/P75_MonthFromQuarter/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDate; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.quarterMonths(LocalDate.now())); System.out.println(); System.out.println(DateCheckers.quarterMonths(1)); System.out.println(DateCheckers.quarterMonths(2)); System.out.println(DateCheckers.quarterMonths(3)); System.out.println(DateCheckers.quarterMonths(4)); System.out.println(); System.out.println(DateCheckers.quarterMonths("Q1")); System.out.println(DateCheckers.quarterMonths("Q2")); System.out.println(DateCheckers.quarterMonths("Q3")); System.out.println(DateCheckers.quarterMonths("Q4")); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P71_YearWeekToDate/src/main/java/modern/challenge/DateConverters.java
Chapter03/P71_YearWeekToDate/src/main/java/modern/challenge/DateConverters.java
package modern.challenge; import java.time.LocalDate; import java.time.temporal.ChronoField; import java.time.temporal.WeekFields; import java.util.Calendar; import java.util.Date; import java.util.Locale; public final class DateConverters { private DateConverters() { throw new AssertionError("Cannot be instantiated"); } public static Date fromV1(int year, int week) { if (year <= 0 || week <= 0) { throw new IllegalArgumentException("Year/week cannot be 0 or negative numbers"); } Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.WEEK_OF_YEAR, week); calendar.set(Calendar.DAY_OF_WEEK, 1); return calendar.getTime(); } public static LocalDate fromV2(int year, int week) { if (year <= 0 || week <= 0) { throw new IllegalArgumentException("Year/week cannot be 0 or negative numbers"); } WeekFields weekFields = WeekFields.of(Locale.getDefault()); return LocalDate.now() .withYear(year) .with(weekFields.weekOfYear(), week) .with(weekFields.dayOfWeek(), 1); } public static int getYearV1(Date date) { if(date == null) { throw new IllegalArgumentException("The given name cannot be null"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.YEAR); } public static int getWeekV1(Date date) { if(date == null) { throw new IllegalArgumentException("The given name cannot be null"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); return calendar.get(Calendar.WEEK_OF_YEAR); } public static int getYearV2(LocalDate date) { if(date == null) { throw new IllegalArgumentException("The given name cannot be null"); } return date.get(ChronoField.YEAR); } public static int getWeekV2(LocalDate date) { if(date == null) { throw new IllegalArgumentException("The given name cannot be null"); } // return date.get(WeekFields.of(Locale.getDefault()).weekOfYear()); return date.get(ChronoField.ALIGNED_WEEK_OF_YEAR); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P71_YearWeekToDate/src/main/java/modern/challenge/Main.java
Chapter03/P71_YearWeekToDate/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.text.ParseException; import java.time.LocalDate; import java.util.Date; public class Main { public static void main(String[] args) throws ParseException { Date date = DateConverters.fromV1(2023, 10); System.out.println("Date: " + date); System.out.println("Year: " + DateConverters.getYearV1(date)); System.out.println("Week: " + DateConverters.getWeekV1(date)); System.out.println(); LocalDate localDate = DateConverters.fromV2(2023, 10); System.out.println("LocalDate: " + localDate); System.out.println("Year: " + DateConverters.getYearV2(localDate)); System.out.println("Week: " + DateConverters.getWeekV2(localDate)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P87_WeeksBetweenTwoDates/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P87_WeeksBetweenTwoDates/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.Date; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static long nrOfWeeks(Date startDate, Date endDate) { if (startDate == null || endDate == null) { throw new IllegalArgumentException("The given dates cannot be null"); } if (startDate.after(endDate)) { throw new IllegalArgumentException("The given start date cannot be after the given end date"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(startDate); int weeks = 0; while (calendar.getTime().before(endDate)) { calendar.add(Calendar.WEEK_OF_YEAR, 1); weeks++; } return weeks; } public static long nrOfWeeks(LocalDateTime startLdt1, LocalDateTime endLdt2) { if (startLdt1 == null || endLdt2 == null) { throw new IllegalArgumentException("The given dates cannot be null"); } return Math.abs(ChronoUnit.WEEKS.between(startLdt1, endLdt2)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P87_WeeksBetweenTwoDates/src/main/java/modern/challenge/Main.java
Chapter03/P87_WeeksBetweenTwoDates/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDateTime; import java.util.Calendar; import java.util.Date; public class Main { public static void main(String[] args) { Calendar c1 = Calendar.getInstance(); c1.set(Calendar.YEAR, 2023); c1.set(Calendar.MONTH, 2); c1.set(Calendar.WEEK_OF_MONTH, 1); Calendar c2 = Calendar.getInstance(); c2.set(Calendar.YEAR, 2023); c2.set(Calendar.MONTH, 4); c2.set(Calendar.WEEK_OF_MONTH, 2); System.out.println(DateCheckers.nrOfWeeks(c1.getTime(), c2.getTime())); LocalDateTime ldt1 = LocalDateTime.now(); LocalDateTime ldt2 = ldt1.minusWeeks(10); LocalDateTime ldt3 = ldt2.plusWeeks(10); LocalDateTime ldt4 = ldt2.minusWeeks(10); System.out.println(); System.out.println(DateCheckers.nrOfWeeks(ldt1, ldt2)); System.out.println(DateCheckers.nrOfWeeks(ldt2, ldt1)); System.out.println(DateCheckers.nrOfWeeks(ldt1, ldt3)); System.out.println(DateCheckers.nrOfWeeks(ldt3, ldt2)); System.out.println(DateCheckers.nrOfWeeks(ldt4, ldt1)); System.out.println(DateCheckers.nrOfWeeks(ldt3, ldt4)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P83_FirstLastDayOfWeek/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P83_FirstLastDayOfWeek/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.DayOfWeek; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import static java.time.temporal.TemporalAdjusters.nextOrSame; import static java.time.temporal.TemporalAdjusters.previousOrSame; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static List<String> weekBoundariesV1(int nrOfWeeks) { if (nrOfWeeks <= 0) { throw new IllegalArgumentException("The given number of weeks must be >= 1"); } List<String> boundaries = new ArrayList<>(); Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); int nrOfDayToAdd = 0; DateFormat df = new SimpleDateFormat("EEE dd/MM/yyyy"); for (int i = 0; i < nrOfWeeks; i++) { calendar.add(Calendar.DATE, nrOfDayToAdd); boundaries.add(df.format(calendar.getTime())); calendar.add(Calendar.DATE, 6); boundaries.add(df.format(calendar.getTime())); nrOfDayToAdd = 1; } return boundaries; } public static List<String> weekBoundariesV2(int nrOfWeeks) { if (nrOfWeeks <= 0) { throw new IllegalArgumentException("The given number of weeks must be >= 1"); } List<String> boundaries = new ArrayList<>(); LocalDate timeline = LocalDate.now(); DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE dd/MM/yyyy"); for (int i = 0; i < nrOfWeeks; i++) { boundaries.add(dtf.format(timeline.with(previousOrSame(DayOfWeek.MONDAY)))); boundaries.add(dtf.format(timeline.with(nextOrSame(DayOfWeek.SUNDAY)))); timeline = timeline.plusDays(7); } return boundaries; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P83_FirstLastDayOfWeek/src/main/java/modern/challenge/Main.java
Chapter03/P83_FirstLastDayOfWeek/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.weekBoundariesV1(3)); System.out.println(DateCheckers.weekBoundariesV2(3)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.time.YearMonth; import java.time.ZoneId; import java.time.temporal.IsoFields; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; import java.time.temporal.TemporalAdjusters; import java.util.Calendar; import java.util.Date; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static Quarter quarterDaysV1(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } LocalDate localDate = date.toInstant() .atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate firstDay = localDate.with(IsoFields.DAY_OF_QUARTER, 1L); // or, like this // LocalDate firstDay = localDate.with(localDate.getMonth().firstMonthOfQuarter()) // .with(TemporalAdjusters.firstDayOfMonth()); LocalDate lastDay = firstDay.plusMonths(2) .with(TemporalAdjusters.lastDayOfMonth()); return new Quarter( Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant()), Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant()) ); } public static Quarter quarterDaysV2(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.DAY_OF_MONTH, 1); // first day calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) / 3 * 3); Date firstDay = calendar.getTime(); // last day calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) / 3 * 3 + 2); calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH)); Date lastDay = calendar.getTime(); return new Quarter(firstDay, lastDay); } public static Quarter quarterDaysV3(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } LocalDate localDate = date.toInstant() .atZone(ZoneId.systemDefault()).toLocalDate(); int year = localDate.getYear(); int quarter = localDate.get(QUARTER_OF_YEAR); LocalDate firstDay = YearMonth.of(year, 1).with(QUARTER_OF_YEAR, quarter).atDay(1); LocalDate lastDay = YearMonth.of(year, 3).with(QUARTER_OF_YEAR, quarter).atEndOfMonth(); return new Quarter( Date.from(firstDay.atStartOfDay(ZoneId.systemDefault()).toInstant()), Date.from(lastDay.atStartOfDay(ZoneId.systemDefault()).toInstant()) ); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/Quarter.java
Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/Quarter.java
package modern.challenge; import java.util.Date; public final class Quarter { private final Date firstDay; private final Date lastDay; public Quarter(Date firstDay, Date lastDay) { this.firstDay = firstDay; this.lastDay = lastDay; } public Date getFirstDay() { return firstDay; } public Date getLastDay() { return lastDay; } @Override public String toString() { return "Quarter{" + "firstDay=" + firstDay + ", lastDay=" + lastDay + '}'; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/Main.java
Chapter03/P74_FirstLastDayOfQuarter/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Date; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.quarterDaysV1(new Date())); System.out.println(DateCheckers.quarterDaysV2(new Date())); System.out.println(DateCheckers.quarterDaysV3(new Date())); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P70_IntToYearMonth/src/main/java/modern/challenge/DateConverters.java
Chapter03/P70_IntToYearMonth/src/main/java/modern/challenge/DateConverters.java
package modern.challenge; import java.time.YearMonth; import java.time.temporal.ChronoField; public final class DateConverters { private DateConverters() { throw new AssertionError("Cannot be instantiated"); } public static YearMonth from(int t) { return YearMonth.of(1970, 1).with(ChronoField.PROLEPTIC_MONTH, t); } public static int to(YearMonth u) { if (u == null) { throw new IllegalArgumentException("The given YearMonth cannot be null"); } return (int) u.getLong(ChronoField.PROLEPTIC_MONTH); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P70_IntToYearMonth/src/main/java/modern/challenge/Main.java
Chapter03/P70_IntToYearMonth/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.text.ParseException; import java.time.YearMonth; public class Main { public static void main(String[] args) throws ParseException { System.out.println("YearMonth to int: " + DateConverters.to(YearMonth.now())); System.out.println("int to YearMonth: " + DateConverters.from(24277)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P85_QuartersBetweenTwoDates/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P85_QuartersBetweenTwoDates/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.time.temporal.IsoFields; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static long nrOfQuarters(LocalDate startDate, LocalDate endDate) { if(startDate == null || endDate == null) { throw new IllegalArgumentException("The given dates cannot be null"); } if(startDate.isAfter(endDate)) { throw new IllegalArgumentException("The given start date cannot be after the given end date"); } return IsoFields.QUARTER_YEARS.between(startDate, endDate); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P85_QuartersBetweenTwoDates/src/main/java/modern/challenge/Main.java
Chapter03/P85_QuartersBetweenTwoDates/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDate; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.nrOfQuarters(LocalDate.MIN, LocalDate.MAX)); System.out.println(DateCheckers.nrOfQuarters( LocalDate.of(2023, 1, 1), LocalDate.of(2024, 1, 1))); System.out.println(DateCheckers.nrOfQuarters( LocalDate.of(2023, 1, 1), LocalDate.of(2023, 2, 1))); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P82_FirstLastDayOfYear/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P82_FirstLastDayOfYear/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import static java.time.temporal.TemporalAdjusters.firstDayOfYear; import static java.time.temporal.TemporalAdjusters.lastDayOfYear; import java.util.Calendar; import java.util.Date; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static String fetchFirstDayOfYearV1(int year, boolean name) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, 1); Date firstDay = calendar.getTime(); if (!name) { return firstDay.toString(); } return new SimpleDateFormat("EEEE").format(firstDay); } public static String fetchFirstDayOfYearV2(int year, boolean name) { LocalDate ld = LocalDate.ofYearDay(year, 1); LocalDate firstDay = ld.with(firstDayOfYear()); if (!name) { return firstDay.toString(); } return DateTimeFormatter.ofPattern("EEEE").format(firstDay); } public static String fetchLastDayOfYearV1(int year, boolean name) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.YEAR, year); calendar.set(Calendar.DAY_OF_YEAR, calendar.getActualMaximum(Calendar.DAY_OF_YEAR)); Date lastDay = calendar.getTime(); if (!name) { return lastDay.toString(); } return new SimpleDateFormat("EEEE").format(lastDay); } public static String fetchLastDayOfYearV2(int year, boolean name) { LocalDate ld = LocalDate.ofYearDay(year, 31); LocalDate lastDay = ld.with(lastDayOfYear()); if (!name) { return lastDay.toString(); } return DateTimeFormatter.ofPattern("EEEE").format(lastDay); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P82_FirstLastDayOfYear/src/main/java/modern/challenge/Main.java
Chapter03/P82_FirstLastDayOfYear/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.fetchFirstDayOfYearV1(2020, false)); System.out.println(DateCheckers.fetchFirstDayOfYearV1(2020, true)); System.out.println(DateCheckers.fetchLastDayOfYearV1(2020, false)); System.out.println(DateCheckers.fetchLastDayOfYearV1(2020, true)); System.out.println(); System.out.println(DateCheckers.fetchFirstDayOfYearV2(2020, false)); System.out.println(DateCheckers.fetchFirstDayOfYearV2(2020, true)); System.out.println(DateCheckers.fetchLastDayOfYearV2(2020, false)); System.out.println(DateCheckers.fetchLastDayOfYearV2(2020, true)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P73_QuarterOfDate/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P73_QuarterOfDate/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.temporal.IsoFields; import java.util.Calendar; import java.util.Date; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static String quarterV1(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } String[] quarters = {"Q1", "Q2", "Q3", "Q4"}; Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int quarter = calendar.get(Calendar.MONTH) / 3; return quarters[quarter]; } public static int quarterV2(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } Calendar calendar = Calendar.getInstance(); // or, new GregorianCalendar(); calendar.setTime(date); return (calendar.get(Calendar.MONTH) / 3) + 1; } public static int quarterV3(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } LocalDate localDate = date.toInstant() .atZone(ZoneId.systemDefault()).toLocalDate(); return localDate.get(IsoFields.QUARTER_OF_YEAR); } public static String quarterV4(Date date) { if (date == null) { throw new IllegalArgumentException("The given date cannot be null"); } return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate() .format(DateTimeFormatter.ofPattern("QQQ")); // QQ escapes Q } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P73_QuarterOfDate/src/main/java/modern/challenge/Main.java
Chapter03/P73_QuarterOfDate/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Date; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.quarterV1(new Date())); System.out.println(DateCheckers.quarterV2(new Date())); System.out.println(DateCheckers.quarterV3(new Date())); System.out.println(DateCheckers.quarterV4(new Date())); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P81_WeekDayName/src/main/java/modern/challenge/Main.java
Chapter03/P81_WeekDayName/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.text.DateFormatSymbols; import java.util.stream.IntStream; public class Main { public static void main(String[] args) { String[] weekdays = new DateFormatSymbols().getWeekdays(); IntStream.range(1, weekdays.length) .mapToObj(t -> String.format("Day: %d -> %s", t, weekdays[t])) .forEach(System.out::println); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P79_SplitDateInEqualIntervals/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P79_SplitDateInEqualIntervals/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.Duration; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.List; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static List<LocalDateTime> splitInEqualIntervals( LocalDateTime start, LocalDateTime end, int n) { if (start == null || end == null) { throw new IllegalArgumentException("The given dates cannot be null"); } if (start.isAfter(end)) { throw new IllegalArgumentException("The given start date must be before the given end date"); } if (n <= 1) { throw new IllegalArgumentException("The given number of intervals must be >= 1"); } Duration range = Duration.between(start, end); Duration interval = range.dividedBy(n - 1); List<LocalDateTime> listOfDates = new ArrayList<>(); LocalDateTime timeline = start; for (int i = 0; i < n - 1; i++) { listOfDates.add(timeline); timeline = timeline.plus(interval); } listOfDates.add(end); return listOfDates; } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P79_SplitDateInEqualIntervals/src/main/java/modern/challenge/Main.java
Chapter03/P79_SplitDateInEqualIntervals/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDateTime; public class Main { public static void main(String[] args) { int n = 25; LocalDateTime end = LocalDateTime.now(); LocalDateTime start = end.minusYears(10); System.out.println(DateCheckers.splitInEqualIntervals(start, end, n)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P77_Stopwatch/src/main/java/modern/challenge/MillisStopwatch.java
Chapter03/P77_Stopwatch/src/main/java/modern/challenge/MillisStopwatch.java
package modern.challenge; import java.util.concurrent.TimeUnit; public final class MillisStopwatch { private long startTime; private long stopTime; private boolean running; public void start() { this.startTime = System.currentTimeMillis(); this.running = true; } public void stop() { this.stopTime = System.currentTimeMillis(); this.running = false; } //elaspsed time in nanoseconds public long getElapsedTime() { if (running) { return System.currentTimeMillis() - startTime; } else { return stopTime - startTime; } } //elaspsed time in millisecods public long elapsedTimeToNanos(long millistime) { return TimeUnit.NANOSECONDS.convert(millistime, TimeUnit.MILLISECONDS); } //elaspsed time in seconds public long elapsedTimeToSeconds(long millistime) { return TimeUnit.SECONDS.convert(millistime, TimeUnit.MILLISECONDS); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P77_Stopwatch/src/main/java/modern/challenge/InstantStopwatch.java
Chapter03/P77_Stopwatch/src/main/java/modern/challenge/InstantStopwatch.java
package modern.challenge; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; public final class InstantStopwatch { private Instant startTime; private Instant stopTime; private boolean running; public void start() { this.startTime = Instant.now(); this.running = true; } public void stop() { this.stopTime = Instant.now(); this.running = false; } //elaspsed time in nanoseconds public long getElapsedTime() { if (running) { return ChronoUnit.NANOS.between(startTime, Instant.now()); } else { return ChronoUnit.NANOS.between(startTime, stopTime); } } //elaspsed time in millisecods public long elapsedTimeToMillis(long nanotime) { return TimeUnit.MILLISECONDS.convert(nanotime, TimeUnit.NANOSECONDS); } //elaspsed time in seconds public long elapsedTimeToSeconds(long nanotime) { return TimeUnit.SECONDS.convert(nanotime, TimeUnit.NANOSECONDS); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P77_Stopwatch/src/main/java/modern/challenge/Main.java
Chapter03/P77_Stopwatch/src/main/java/modern/challenge/Main.java
package modern.challenge; public class Main { public static void main(String[] args) throws InterruptedException { InstantStopwatch is = new InstantStopwatch(); is.start(); Thread.sleep(1000); // sleep 1s long betais = is.getElapsedTime(); Thread.sleep(2000); // sleep 2s is.stop(); long alfais = is.getElapsedTime(); System.out.println(betais + " nano"); System.out.println(is.elapsedTimeToMillis(betais) + " millis"); System.out.println(is.elapsedTimeToSeconds(betais) + " seconds"); System.out.println(); System.out.println(alfais + " nano"); System.out.println(is.elapsedTimeToMillis(alfais) + " millis"); System.out.println(is.elapsedTimeToSeconds(alfais) + " seconds"); System.out.println("\n--------------------------------------------------\n"); MillisStopwatch ms = new MillisStopwatch(); ms.start(); Thread.sleep(1000); // sleep 1s long betams = ms.getElapsedTime(); Thread.sleep(2000); // sleep 2s ms.stop(); long alfams = ms.getElapsedTime(); System.out.println(betams + " millis"); System.out.println(ms.elapsedTimeToNanos(betams) + " nanos"); System.out.println(ms.elapsedTimeToSeconds(betams) + " seconds"); System.out.println(); System.out.println(alfams + " millis"); System.out.println(ms.elapsedTimeToNanos(alfams) + " nanos"); System.out.println(ms.elapsedTimeToSeconds(alfams) + " seconds"); System.out.println("\n--------------------------------------------------\n"); NanoStopwatch ns = new NanoStopwatch(); ns.start(); Thread.sleep(1000); // sleep 1s long betans = ns.getElapsedTime(); Thread.sleep(2000); // sleep 2s ns.stop(); long alfans = ns.getElapsedTime(); System.out.println(betans + " nano"); System.out.println(ns.elapsedTimeToMillis(betans) + " millis"); System.out.println(ns.elapsedTimeToSeconds(betans) + " seconds"); System.out.println(); System.out.println(alfans + " nano"); System.out.println(ns.elapsedTimeToMillis(alfans) + " millis"); System.out.println(ns.elapsedTimeToSeconds(alfans) + " seconds"); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P77_Stopwatch/src/main/java/modern/challenge/NanoStopwatch.java
Chapter03/P77_Stopwatch/src/main/java/modern/challenge/NanoStopwatch.java
package modern.challenge; import java.util.concurrent.TimeUnit; public final class NanoStopwatch { private long startTime; private long stopTime; private boolean running; public void start() { this.startTime = System.nanoTime(); this.running = true; } public void stop() { this.stopTime = System.nanoTime(); this.running = false; } //elaspsed time in nanoseconds public long getElapsedTime() { if (running) { return System.nanoTime() - startTime; } else { return stopTime - startTime; } } //elaspsed time in millisecods public long elapsedTimeToMillis(long nanotime) { return TimeUnit.MILLISECONDS.convert(nanotime, TimeUnit.NANOSECONDS); } //elaspsed time in seconds public long elapsedTimeToSeconds(long nanotime) { return TimeUnit.SECONDS.convert(nanotime, TimeUnit.NANOSECONDS); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P86_ConvertCalendarToLocalDateTime/src/main/java/modern/challenge/DateConverters.java
Chapter03/P86_ConvertCalendarToLocalDateTime/src/main/java/modern/challenge/DateConverters.java
package modern.challenge; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.Calendar; import java.util.Date; public final class DateConverters { private DateConverters() { throw new AssertionError("Cannot be instantiated"); } public static LocalDateTime toLocalDateTimeV1(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The given calendar cannot be null"); } // for LocalDate use LocalDate.ofInstant() return LocalDateTime.ofInstant(calendar.toInstant(), // or, Instant.ofEpochMilli(calendar.getTimeInMillis()) ZoneId.systemDefault()); } public static LocalDateTime toLocalDateTimeV2(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The given calendar cannot be null"); } Date date = calendar.getTime(); return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); } public static ZonedDateTime toZonedDateTimeV1(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The given calendar cannot be null"); } return ZonedDateTime.ofInstant(calendar.toInstant(), // or, Instant.ofEpochMilli(calendar.getTimeInMillis()) calendar.getTimeZone().toZoneId()); } public static ZonedDateTime toZonedDateTimeV2(Calendar calendar) { if (calendar == null) { throw new IllegalArgumentException("The given calendar cannot be null"); } Date date = calendar.getTime(); return date.toInstant().atZone(calendar.getTimeZone().toZoneId()); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P86_ConvertCalendarToLocalDateTime/src/main/java/modern/challenge/Main.java
Chapter03/P86_ConvertCalendarToLocalDateTime/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class Main { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); calendar.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta")); System.out.println(DateConverters.toLocalDateTimeV1(calendar)); // ignore calendar's time zone System.out.println(DateConverters.toZonedDateTimeV1(calendar)); // use calendar's time zone System.out.println(DateConverters.toLocalDateTimeV2(calendar)); // ignore calendar's time zone System.out.println(DateConverters.toZonedDateTimeV2(calendar)); // use calendar's time zone } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P84_MiddleOfTheMonth/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P84_MiddleOfTheMonth/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.util.Calendar; import java.util.Date; public final class DateCheckers { private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static Date middleOfTheMonthV1(Date date) { if(date == null) { throw new IllegalArgumentException("The given date cannot be null"); } Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); int middleDay = daysInMonth / 2; calendar.set(Calendar.DAY_OF_MONTH, middleDay); return calendar.getTime(); } public static LocalDate middleOfTheMonthV2(LocalDate date) { if(date == null) { throw new IllegalArgumentException("The given date cannot be null"); } return LocalDate.of(date.getYear(), date.getMonth(), date.lengthOfMonth() / 2); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P84_MiddleOfTheMonth/src/main/java/modern/challenge/Main.java
Chapter03/P84_MiddleOfTheMonth/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDate; import java.util.Date; public class Main { public static void main(String[] args) { System.out.println(DateCheckers.middleOfTheMonthV1(new Date())); System.out.println(DateCheckers.middleOfTheMonthV2(LocalDate.now())); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P76_PregnancyDueDateCalculator/src/main/java/modern/challenge/DateCheckers.java
Chapter03/P76_PregnancyDueDateCalculator/src/main/java/modern/challenge/DateCheckers.java
package modern.challenge; import java.time.LocalDate; import java.time.temporal.ChronoUnit; public final class DateCheckers { public static final int PREGNANCY_WEEKS = 40; public static final int PREGNANCY_DAYS = PREGNANCY_WEEKS * 7; private DateCheckers() { throw new AssertionError("Cannot be instantiated"); } public static void pregnancyCalculator(LocalDate firstDay) { firstDay = firstDay.plusDays(PREGNANCY_DAYS); System.out.println("Due date: " + firstDay); LocalDate today = LocalDate.now(); long betweenDays = Math.abs(ChronoUnit.DAYS.between(firstDay, today)); long diffDays = PREGNANCY_DAYS - betweenDays; long weekNr = diffDays / 7; long weekPart = diffDays % 7; String week = weekNr + " | " + weekPart; System.out.println("Days remaining: " + betweenDays); System.out.println("Days in: " + diffDays); System.out.println("Week: " + week); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false
PacktPublishing/Java-Coding-Problems-Second-Edition
https://github.com/PacktPublishing/Java-Coding-Problems-Second-Edition/blob/47b7c834407a607580baf8e3a23c1c24c24b8bc0/Chapter03/P76_PregnancyDueDateCalculator/src/main/java/modern/challenge/Main.java
Chapter03/P76_PregnancyDueDateCalculator/src/main/java/modern/challenge/Main.java
package modern.challenge; import java.time.LocalDate; public class Main { public static void main(String[] args) { DateCheckers.pregnancyCalculator(LocalDate.now().minusDays(100)); } }
java
MIT
47b7c834407a607580baf8e3a23c1c24c24b8bc0
2026-01-05T02:37:06.170961Z
false