Quick Java 8 Streams Refresh — From Revisiting to Refining: Sometimes, going back to the basics helps you rediscover how powerful simple concepts can be. I recently took some time to refresh my Java 8 Stream skills I’ve attached the complete Java file — hoping it can serve as a handy reference for anyone revisiting Streams or learning them in depth. Here’s what’s inside. 🔹 Grouping and aggregation 🔹 Calculating totals using both Collectors.summingLong() and reduce() 🔹 Word and character frequency analysis 🔹 Merging and transforming multiple lists into one stream 🔹 Detecting duplicates, unique elements, and even the second-highest transaction 🔹 Sorting complex objects with Comparator.comparing() 🔹 Reversing words, removing nulls, partitioning data, and more Each snippet reminded me how Streams simplify Java code — making it more declarative, expressive, and concise. Here’s a small example ________________________________________________________________________ // Find second highest credit transaction List<Transaction> transactions2 = new ArrayList<>(); transactions2.add(new Transaction(transactionType.CREDIT, 10)); transactions2.add(new Transaction(transactionType.CREDIT, 50)); transactions2.add(new Transaction(transactionType.DEBIT, 100)); transactions2.add(new Transaction(transactionType.DEBIT, 20)); transactions2.add(new Transaction(transactionType.CREDIT, 30)); Transaction secondHighest = transactions2.stream() .filter(t -> t.getType() == transactionType.CREDIT) .sorted(Comparator.comparingInt(Transaction::getAmount).reversed()) .skip(1) .findFirst() .get(); System.out.println(secondHighest); ________________________________________________________________________ Full code attached below — feel free to explore and reuse! Let’s keep learning, refining, and sharing knowledge together. #Java #Java8 #Streams #FunctionalProgramming #CleanCode #CodingPractice #DeveloperCommunity #LearningInPublic
Java 8 Streams: A Refresh on Basics and Advanced Techniques
More Relevant Posts
-
In Java, there are several ways to create and run threads, Spring Boot also have @Async annotation to run method code as thread. 1. Extending the Thread class You can create a subclass of Thread and override the run() method. ✅ Example: class MyThread extends Thread { @Override public void run() { System.out.println("Thread running " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } } 🧩 2. Implementing the Runnable interface ✅ Example: class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 🟢 Why preferred: Allows you to extend another class (since Java supports only single inheritance). ⚡ 3. Using Anonymous Class You can create and start a thread in one line using an anonymous inner class. ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread running using Anonymous class"); } }); t1.start(); } } 💡 4. Using Lambda Expression (Java 8+) ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(() -> { System.out.println("Thread running using Lambda expression"); }); t1.start(); } } ⚙️ 5. Using ExecutorService (Thread Pool) For multiple or managed threads, use an Executor Service. ✅ Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println("Thread 1 using ExecutorService")); executor.submit(() -> System.out.println("Thread 2 using ExecutorService")); executor.shutdown(); } } 🟢 Advantages: Reuses threads (avoids overhead of creating new threads repeatedly) Supports async tasks and better error handling 🧠 6. Using Callable and Future (for return values) Callable is like Runnable, but can return a value and throw exceptions. ✅ Example: import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<String> task = () -> { return "Result from thread: " + Thread.currentThread().getName(); }; Future<String> future = executor.submit(task); System.out.println(future.get()); executor.shutdown(); } }
To view or add a comment, sign in
-
☕💻 JAVA THREADS CHEAT SHEET 🔹 🧠 What is a Thread? 👉 The smallest unit of execution in a process. Each thread runs independently but shares memory & resources with others. 🧩 Enables multitasking and parallel execution. 🔹 ⚙️ What is a Process? 👉 An executing instance of a program. Each process has its own memory space and can run multiple threads. 🧵 Types of Threads 👤 1️⃣ User Threads ✅ Created by users or apps. ✅ JVM waits for them before exit. 💡 Example: Thread t = new Thread(() -> System.out.println("User Thread")); t.start(); 👻 2️⃣ Daemon Threads ⚙️ Background threads (e.g., Garbage Collector). ❌ JVM doesn’t wait for them. 💡 Example: Thread d = new Thread(() -> {}); d.setDaemon(true); d.start(); 🚀 Creating Threads 🔸 Extending Thread: class MyThread extends Thread { public void run(){ System.out.println("Running..."); } } new MyThread().start(); 🔸 Implementing Runnable: new Thread(() -> System.out.println("Runnable running...")).start(); 🔄 Thread Lifecycle 🧩 NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED 🕹️ Common Thread Methods 🧩 Method ⚡ Use start() Start a thread run() Thread logic sleep(ms) Pause execution join() Wait for thread interrupt() Interrupt thread setDaemon(true) Make daemon thread 🔒 Synchronization Prevents race conditions when multiple threads share data. synchronized void increment() { count++; } 💬 Thread Communication Use wait(), notify(), and notifyAll() for coordination. 🧠 Must be called inside a synchronized block. ⚡ Executor Framework (Thread Pooling) Efficient thread reuse for better performance. ExecutorService ex = Executors.newFixedThreadPool(3); ex.submit(() -> System.out.println("Task executed")); ex.shutdown(); 🏁 Pro Tips ✅ Prefer Runnable / ExecutorService ✅ Handle InterruptedException ✅ Avoid deprecated methods (stop(), suspend()) ✅ Use java.util.concurrent for safe multithreading 📢 Boost Your Skills 🚀 #Java #Threads #Multithreading #Concurrency #JavaDeveloper #JavaInterview #JavaCoding #JavaProgrammer #CodeNewbie #ProgrammingTips #DeveloperCommunity #CodingLife #LearnJava #JavaCheatSheet #ThreadPool #TechInterview #SoftwareEngineer #CodeWithMe #JavaExperts #BackendDeveloper #JavaLearning #JavaBasics #OOP #CodeDaily #CodingJourney #DevCommunity #JavaLovers #TechCareers #CodeSmarter #100DaysOfCode
To view or add a comment, sign in
-
-
💡 Why Does Java Still Use Primitive Data Types in 2025? With all the progress in Java — from records and sealed classes to virtual threads — you might wonder: 👉 Why does Java still have int, double, boolean, etc., instead of just using objects like Integer or Double everywhere? Let’s break it down 👇 ⚙️ 1️⃣ Performance at the Core Primitives are stored directly on the stack (or in registers), not as heap objects. That means: No object allocation overhead No garbage collection pressure Faster CPU-level access 📘 Example: int sum = 0; for (int i = 0; i < 1_000_000; i++) { sum += i; } This loop runs orders of magnitude faster than using Integer sum = 0; because the latter constantly creates and boxes new Integer objects. 🧠 2️⃣ Memory Efficiency Every object in Java has header metadata (usually 12–16 bytes). With primitives, there’s no per-value overhead — crucial when handling large data arrays. int[] numbers = new int[1_000_000]; // ~4 MB Integer[] numbersObj = new Integer[1_000_000]; // ~16 MB+ due to object headers That’s a 4x+ difference in memory use — and it matters in high-performance systems. 🔄 3️⃣ Simplicity in Low-Level Computation Primitives give direct control over arithmetic and bitwise operations without abstraction layers. This is essential for: Numeric computations Game engines High-frequency trading systems Data processing pipelines 🚀 4️⃣ But What About “Everything is an Object”? Java’s design balances OO principles with practical performance. Yes, Integer, Double, and Boolean exist — but they’re wrappers, not replacements. You can use them when you need features like null handling, generics, or collections. 🔬 5️⃣ Project Valhalla (Coming Soon) Java’s future (Project Valhalla) aims to introduce value types — combining the performance of primitives with the flexibility of objects. That might finally bridge this gap. But until then, primitives remain the foundation of Java performance. 🏁 In short: Java keeps primitives because they’re fast, memory-efficient, and predictable — all vital for scalable, low-latency systems. Object wrappers add flexibility — but primitives keep Java grounded in performance reality. 💬 What’s your take — should Java eventually unify primitives and objects, or keep them separate for clarity and performance? #Java #Performance #Programming #SoftwareEngineering #JVM #Javadeveloper
To view or add a comment, sign in
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Multi-Release JAR" ka hidden feature!🤯 ```java // Java 8 version - base code public class TimeUtils { public static String getTime() { return "Legacy time: " + new Date(); } } // Java 11 version - META-INF/versions/11/TimeUtils.java public class TimeUtils { public static String getTime() { return "Modern time: " + Instant.now(); } } ``` Secret: Ek hi JAR mein multiple Java versions ke liye alag-alag class files ho sakti hain!💀 --- Post 2: Java ka "ConstantDynamic" - invokedynamic for constants!🔥 ```java public class ConstantDynamic { // Java 11+ mein constants bhi dynamically resolve ho sakte hain public static final String DYNAMIC_CONSTANT = ConstantDescs.of("Dynamically resolved constant"); // Bytecode level par invokedynamic use karta hai // instead of constant pool entry! } ``` Internal Magic: · Traditional: Constant Pool → LDC instruction · New: ConstantDynamic → invokedynamic instruction · Dynamic constant resolution at runtime! 💡 --- Post 3: Java ka "Vector API" - SIMD operations ka raaz!🚀 ```java import jdk.incubator.vector.*; public class VectorMagic { public static void main(String[] args) { IntVector a = IntVector.fromArray(IntVector.SPECIES_256, new int[]{1,2,3,4,5,6,7,8}, 0); IntVector b = IntVector.fromArray(IntVector.SPECIES_256, new int[]{8,7,6,5,4,3,2,1}, 0); IntVector result = a.add(b); // ✅ 8 operations ek saath! // CPU level par SIMD instructions use karta hai } } ``` Performance: 10x faster for mathematical operations!💪 --- Post 4: Java ka "Heap Allocation" ka hidden alternative!🔮 ```java import java.lang.foreign.*; public class OffHeapMagic { public static void main(String[] args) { // Heap se bahar memory allocate karo! try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(100); // Direct OS memory access - no GC overhead! segment.set(ValueLayout.JAVA_INT, 0, 42); int value = segment.get(ValueLayout.JAVA_INT, 0); } } } ``` Benefits: · Zero GC pressure · Direct memory access · C-like performance 💀 --- Bhai, yeh features toh aane wali Java generations ke liye hain! 😎
To view or add a comment, sign in
-
Java Has Evolved — Here’s What Changed from JDK 8 to JDK 17 🚀 ☕ JDK 8 (2014) — The Modern Java Revolution Major Features: ✅ Lambda Expressions → Functional programming style ✅ Stream API → Process collections efficiently ✅ Functional Interfaces → @FunctionalInterface, Predicate, Function, etc. ✅ Default & Static Methods in Interfaces ✅ Optional Class → Avoid NullPointerException ✅ Date and Time API (java.time) → New modern date/time handling ✅ Nashorn JavaScript Engine ⚙️ JDK 9 (2017) — Modular Java Key Features: 🧩 Module System (Project Jigsaw) → module-info.java JShell (REPL) → Interactive Java shell Stream API Enhancements → takeWhile(), dropWhile(), iterate() Private Methods in Interfaces Factory Methods for Collections → List.of(), Set.of(), Map.of() ⚙️ JDK 10 (2018) — Developer Productivity Key Features: 🔹 Local Variable Type Inference → var keyword Garbage Collector Improvements (G1) Application Class-Data Sharing Parallel Full GC for G1 ⚙️ JDK 11 (2018) — LTS Release (Long-Term Support) Key Features: 🌐 New HttpClient API → Replaces old HttpURLConnection String Methods → isBlank(), lines(), strip(), repeat() Lambda Parameter Type Inference Removed Java EE & CORBA modules Single-file Source Code Execution → java Hello.java ⚙️ JDK 12 (2019) Key Features: 🧮 Switch Expressions (Preview) → switch usable as an expression JVM Constants API Shenandoah GC (low-pause-time GC) ⚙️ JDK 13 (2019) Key Features: 📜 Text Blocks (Preview) → Multi-line strings using """ Switch Expression Enhancements Reimplementation of Legacy Socket API ⚙️ JDK 14 (2020) Key Features: 🧱 Records (Preview) → Immutable data carriers (record Point(int x, int y)) 🕵️ Pattern Matching for instanceof (Preview) 🧍♂️ Helpful NullPointerException Messages Switch Expressions (Standardized) ⚙️ JDK 15 (2020) Key Features: 🧩 Sealed Classes (Preview) → Restrict which classes can extend a class Text Blocks (Standard) Hidden Classes EdDSA Algorithm Support (New Crypto) ⚙️ JDK 16 (2021) Key Features: 🧱 Records (Standard) 🕵️ Pattern Matching for instanceof (Standard) JEP 391: macOS/AArch64 support (Apple M1) Vector API (Incubator) Strong Encapsulation of JDK Internals ⚙️ JDK 17 (2021) — LTS Release Key Features: 🧩 Sealed Classes (Standard) 🕵️ Pattern Matching for switch (Preview) 🧱 Enhanced Pseudo-Random Number Generators (PRNG) Foreign Function & Memory API (Incubator) New macOS Rendering Pipeline (Metal API) Removed Deprecated RMI Activation, Applet API, etc.
To view or add a comment, sign in
-
🚀 Top Java 11 Features You Should Know Java 11 (LTS) brings several powerful updates for developers. Here’s a quick breakdown of the highlights: 1️⃣ Run Java Files Without Compilation 💻 Previously, we had to compile Java programs with javac and then run the .class files. Now, for single-file programs, you can run directly: java MyProgram.java Java compiles temporarily in memory, executes it, and no .class file is created. ⚠️ This means only the source code is needed for sharing, not compiled bytecode. 2️⃣ New String Methods 🧩 Java 11 adds several handy utilities to the String class: " ".isBlank(); // true "Hello\nWorld".lines().forEach(System.out::println); " Java ".strip(); // "Java" (Unicode-aware) "Hi ".repeat(3); // "Hi Hi Hi " 3️⃣ Files Utility Enhancements 📂 Simpler file I/O with Files.readString() and Files.writeString(): Path path = Files.writeString(Files.createTempFile("demo", ".txt"), "Java 11"); String content = Files.readString(path); System.out.println(content); // "Java 11" 4️⃣ var in Lambda Parameters ⚡ var can now be used in lambda expressions, allowing annotations and improving readability: List<String> list = List.of("A", "B", "C"); list.stream() .map((var s) -> s.toLowerCase()) .forEach(System.out::println); Note: * var can also be used for local variables. * It is not a datatype, but a type inference reference — the compiler determines the actual type at compile time. * For local variables, var must be initialized at the time of declaration so the compiler can infer the type. * This feature for local variables was introduced in Java 10. 5️⃣ HTTP Client Standardization 🌐 The experimental HTTP client is now fully standardized in java.net.http: var client = HttpClient.newHttpClient(); var request = HttpRequest.newBuilder() .uri(URI.create("https://api.github.com")) .build(); var response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println(response.body()); Supports HTTP/1.1, HTTP/2, and WebSockets. 6️⃣ Garbage Collector Improvements 🧹 Epsilon GC: No-op GC for performance testing. ZGC: Low-latency garbage collector (experimental). 7️⃣ Deprecations & Removals 🧾 Java EE & CORBA modules removed (javax.xml.bind, java.activation) JavaFX removed from JDK (available separately) 8️⃣ Java Flight Recorder (JFR) ☁️ Integrated into OpenJDK for profiling and production monitoring. 9️⃣ Nest-Based Access Control 🏗️ Simplifies private access between nested classes, removing synthetic bridge methods. 🔟 TLS 1.3 Support ⚙️ Enhanced security and performance in JSSE with TLS 1.3. 🔥 Java enthusiasts, unite! 🔥 Love exploring juicy Java tips, tricks, and features? Follow me for insights that make coding fun and practical! 💻☕ Let’s level up your Java game! 🚀 #Java11 #JavaLTS #Programming #SoftwareDevelopment #CleanCode #JavaDevelopers #FullStackDevelopment #TechTrends #CodingTips #JavaFeatures #JavaFullStackDevelopment #BackendDevelopment #CodeWithMohan
To view or add a comment, sign in
-
Java ke parallel universe ke secrets! 🔥 --- Post 1: Java ka "Hidden Class" API - Java 15+ ka best kept secret!🤯 ```java import java.lang.invoke.*; public class HiddenClassMagic { public static void main(String[] args) throws Throwable { MethodHandles.Lookup lookup = MethodHandles.lookup(); byte[] classBytes = getClassBytes(); // Bytecode bytes // Hidden class banayi jo reflection mein visible nahi hogi! Class<?> hiddenClass = lookup.defineHiddenClass(classBytes, true).lookupClass(); MethodHandle mh = lookup.findStatic(hiddenClass, "secretMethod", MethodType.methodType(void.class)); mh.invoke(); // ✅ Chalega but Class.forName() se nahi milegi! } } ``` Secret: Hidden classes reflection mein visible nahi hoti, par perfectly work karti hain!💀 --- Post 2: Java ka "Thread Local Handshakes" ka JVM level magic!🔥 ```java public class ThreadHandshake { static { // JVM internally sab threads ko pause kiye bina // single thread ko stop kar sakta hai! // Ye Java 9+ mein aaya for better profiling // -XX:ThreadLocalHandshakes=true } } ``` Internal Use Cases: · Stack sampling without stopping all threads · Lightweight performance monitoring · Better garbage collection Secret: JVM ab single thread ko individually manipulate kar sakta hai! 💡 --- Post 3: Java ka "Contended" annotation for false sharing prevention!🚀 ```java import jdk.internal.vm.annotation.Contended; public class FalseSharingFix { // Ye do variables different cache lines mein store honge! @Contended public long value1 = 0L; @Contended public long value2 = 0L; } ``` JVM Option Required: ``` -XX:-RestrictContended ``` Performance Impact: Multi-threaded apps mein 30-40%performance improvement! 💪 --- Post 4: Java ka "CDS Archives" - Application startup 10x faster!🔮 ```java // Kuch nahi karna - bas JVM options use karo: // Dump CDS archive: // -Xshare:dump -XX:SharedArchiveFile=app.jsa // Use CDS archive: // -Xshare:on -XX:SharedArchiveFile=app.jsa ``` Internal Magic: · Pre-loaded classes shared memory mein · Startup time dramatically kam · Memory footprint reduce Result: Spring Boot apps 3-4 seconds se 400-500ms startup!💀 ---
To view or add a comment, sign in
-
Java ke woh secrets jo documentation mein bhi nahi hain! 🔥 --- Post 1: Java Compiler ka "Negative Array Size" bug!🤯 ```java public class NegativeArray { public static void main(String[] args) { try { int[] arr = new int[-5]; // ❌ Negative size } catch (NegativeArraySizeException e) { // Ye exception JVM ke internal memory allocation se aati hai // Java specification ke according, yeh error compulsory hai! } } } ``` Secret: Java specification page 329: "Array creation with negative size must throw NegativeArraySizeException" - ye rule JVM implementers ko follow karna compulsory hai! 💀 --- Post 2: Java ka "Floating-Point Non-Associativity" paradox!🔥 ```java public class FloatingParadox { public static void main(String[] args) { double a = 1.0e308; // Very large number double b = -1.0e308; // Very large negative double c = 1.0; double result1 = (a + b) + c; // (0) + 1 = 1 double result2 = a + (b + c); // Infinity + (-Infinity) = NaN System.out.println(result1); // 1.0 System.out.println(result2); // NaN } } ``` Mathematical Paradox: Java floating-point arithmetic associative nahi hai! IEEE 754 standard ka hidden rule! 💡 --- Post 3: Java ka "Class File Magic Number" ka raaz!🚀 ```java // Har .class file ke start mein ye 4 bytes hote hain: // CA FE BA BE - "Coffee Baby"! // Ye Java creators ne randomly choose kiya tha 1995 mein! public class MagicNumber { public static void main(String[] args) throws Exception { byte[] classBytes = java.nio.file.Files.readAllBytes( java.nio.file.Paths.get("MagicNumber.class") ); // First 4 bytes check karo System.out.printf("%02X %02X %02X %02X", classBytes[0], classBytes[1], classBytes[2], classBytes[3]); // Output: CA FE BA BE } } ``` Historical Secret: James Gosling team ne ye magic number randomly rakha tha! 💪 --- Post 4: Java ka "Null Type" ka compiler-level existence!🔮 ```java public class NullType { public static void main(String[] args) { // Java compiler internally null ka ek special type maintain karta hai // called "the null type" - jiska koi name nahi hota! String s = null; Integer i = null; // Compiler null ko kisi bhi reference type assign kar sakta hai // kyunki uska apna alag "null type" hai! } } ``` Language Theory: Java Language Specification §4.1: "There is also a special null type, the type of the expression null" - ye type sirf compiler internally use karta hai! 💀
To view or add a comment, sign in
-
Java ke deepest secrets! 🔥 --- Post 1: Java ka "Hidden Synthetic Methods" ka raaz!🤯 ```java public class SyntheticMagic { private String secret = "Hidden"; // Java compiler internally ye method banata hai: // synthetic access$000() - private variable access ke liye } class InnerClass { void show() { SyntheticMagic obj = new SyntheticMagic(); // obj.secret - ye access karne ke liye compiler // synthetic method generate karta hai! } } ``` Secret: Java compiler private members access karne ke liye hidden synthetic methods banata hai!💀 --- Post 2: Java ka "Bridge Methods" ka internal magic!🔥 ```java class Parent<T> { public void set(T value) { } } class Child extends Parent<String> { public void set(String value) { } // Override } ``` Compile Time pe Java ye bridge method add karta hai: ```java // Synthetic bridge method public void set(Object value) { set((String) value); // Type cast karke actual method call } ``` Kyun? Type erasure ke baad bhi polymorphism maintain karne ke liye!💡 --- Post 3: Java ka "Constant Pool" ka hidden storage!🚀 ```java public class ConstantPoolSecrets { public static void main(String[] args) { String s1 = "Java"; String s2 = "Java"; int num = 100; float f = 3.14f; } } ``` .class file ke constant pool mein store hoga: ``` Constant pool: #1 = String #2 // "Java" #2 = Utf8 Java #3 = Integer 100 #4 = Float 3.14f ``` Secret: Har.class file ka apna constant pool hota hai jisme sab constants store hote hain!💪 --- Post 4: Java ka "Exception Handler" ka bytecode magic!🔮 ```java public class ExceptionSecrets { public static void main(String[] args) { try { riskyMethod(); } catch (RuntimeException e) { handleError(); } } } ``` Bytecode Level Exception Table: ``` Exception table: from to target type 0 4 7 Class java/lang/RuntimeException ``` Internal Working: · from to to → try block range · target → catch block start · type → kis exception ka handle hoga 💀 --- yeh secrets toh Java bytecode engineers ke dil mein chhupe hain! 😎
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Thanks for spending time on Java streams and sharing this.