Java Map.Entry Cheat Sheet: Sorted() & Max() Made Simple ------------------------------------------------------------ MAP.ENTRY SYNTAX FOR SORTED AND MAX ----------------------------------- 1. SORTED BY KEY (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey()) 2. SORTED BY KEY (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 3. SORTED BY VALUE (ASC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue()) 4. SORTED BY VALUE (DESC) map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())) 5. MAX BY VALUE map.entrySet() .stream() .max(Map.Entry.comparingByValue()) 6. MIN BY VALUE map.entrySet() .stream() .min(Map.Entry.comparingByValue()) 7. MAX BY KEY map.entrySet() .stream() .max(Map.Entry.comparingByKey()) 8. MIN BY KEY map.entrySet() .stream() .min(Map.Entry.comparingByKey())
Java Map.Entry Sorted and Max Examples
More Relevant Posts
-
Ever wondered why we need a "StringBuilder" in Java when we already have "String"? 🤔 At first glance, "String" seems perfectly fine for handling text. But the real difference shows up when we start modifying or concatenating strings multiple times. 👉 The key point: Strings in Java are immutable. This means every time you concatenate a string, a new object is created in memory. Example: String str = "Hello"; str = str + " World"; str = str + "!"; Behind the scenes, this creates multiple objects: - "Hello" - "Hello World" - "Hello World!" This repeated object creation increases memory usage and puts extra load on the Garbage Collector (GC). 🚨 In scenarios like loops or heavy string manipulation, this can significantly impact performance. So where does "StringBuilder" help? "StringBuilder" is mutable, meaning it modifies the same object instead of creating new ones. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); sb.append("!"); ✅ Only one object is used and updated internally ✅ Faster performance ✅ Less memory overhead ✅ Reduced GC pressure When should you use it? ✔ When performing frequent string modifications ✔ Inside loops ✔ When building dynamic strings (logs, queries, JSON, etc.) 💡 Quick takeaway: - Use "String" for simple, fixed text - Use "StringBuilder" for dynamic or repeated modifications 💥 Advanced Tip: StringBuilder Capacity vs Length Most developers know StringBuilder is faster—but here’s something interviewers love 👇 👉 length() = actual number of characters 👉 capacity() = total allocated memory By default, capacity starts at 16 and grows dynamically when needed: ➡️ New capacity = (old * 2) + 2 💡 Why it matters? Frequent resizing creates new internal arrays and copies data → impacts performance. ✅ Pro tip: When working with loops or large data, initialize capacity in advance: StringBuilder sb = new StringBuilder(1000); Understanding this small concept can make a big difference in writing efficient Java code 🚀 #Java #Programming #Performance #CodingTips #Developers
To view or add a comment, sign in
-
-
Stuck in Java 8? Here’s a 2-minute guide to the most asked LTS features! ☕️🚀 If you're preparing for a Java interview, you need to know more than just the basics. Interviewers are increasingly focusing on the evolution from Java 8 to 21. Here is a quick breakdown of the "Must-Know" features for your next technical round: 🌱 Java 8: The Functional Revolution The foundation of modern Java. Lambda Expressions: Passing behavior as a parameter. 1.list.forEach(item -> System.out.println(item)); 2.(var x, var y) -> x + y; Stream API: Declarative data processing (Filter, Map, Sort). Optional Class: Say goodbye to NullPointerException. Default Methods: Adding logic to interfaces without breaking old code. 🧹 Java 11: Modernization & Cleanup Var for Lambdas: Standardizes local variable syntax in functional code. (var x, var y) -> x + y; New HTTP Client: Finally, a modern, asynchronous way to handle web requests. String Utilities: Handy methods like .isBlank(), .strip(), and .repeat(). 🏗️ Java 17: Expressive Syntax Focuses on reducing boilerplate and better inheritance control. Sealed Classes: Restrict which classes can extend your code. public sealed class Shape permits Circle, Square {} Records: One-liner immutable data classes. public record User(String name, int id) {} Text Blocks: Clean multi-line strings without the \n mess. ⚡ Java 21: High-Performance Concurrency The current gold standard for scalability. Virtual Threads: Lightweight threads that make I/O-bound tasks incredibly fast. Pattern Matching for Switch: Cleaner type checking. switch (obj) { case Integer i -> System.out.println("Int: " + i); case String s -> System.out.println("String: " + s); default -> System.out.println("Unknown"); } Sequenced Collections: Better control over the order of elements (First/Last). #Knowledge Sharer #Learning
To view or add a comment, sign in
-
𝗝𝗮𝘃𝗮 𝗦𝗲𝗿𝗶𝗲𝘀 – 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 & 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻𝘀 (𝗦𝗶𝗺𝗽𝗹𝗲 𝗚𝘂𝗶𝗱𝗲) Java 8 introduced a powerful concept: 👉 Functional Programming in Java The core of it is: • Functional Interface • Lambda Expression Let’s understand both simply 👇 🔹 What is a 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲? A 𝗙𝘂𝗻𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗜𝗻𝘁𝗲𝗿𝗳𝗮𝗰𝗲 is an interface that has only ONE abstract method. Example: @FunctionalInterface interface MyInterface { void sayHello(); } Key points: • Only one abstract method • Can have multiple default/static methods • Used with Lambda Expressions Real examples in Java: Runnable Callable Comparator 🔹 What is a 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻? A 𝗟𝗮𝗺𝗯𝗱𝗮 𝗘𝘅𝗽𝗿𝗲𝘀𝘀𝗶𝗼𝗻 is a short way to implement a functional interface. 👉 Instead of writing full class → write simple function Without Lambda MyInterface obj = new MyInterface() { public void sayHello() { System.out.println("Hello"); } }; With Lambda MyInterface obj = () -> { System.out.println("Hello"); }; ✔ Less code ✔ More readable ✔ Modern Java style 🔹 How Lambda Works Internally 👉 Lambda provides implementation for the single abstract method of functional interface. So this: () -> System.out.println("Hello"); Means: 👉 “Implement the method sayHello()” Syntax of Lambda (parameters) -> { body } Examples: // No parameter () -> System.out.println("Hello"); // One parameter x -> x * x; // Multiple parameters (a, b) -> a + b; 🔹 Functional Interface + Lambda (Full Example) @FunctionalInterface interface Add { int sum(int a, int b); } public class Main { public static void main(String[] args) { Add obj = (a, b) -> a + b; System.out.println(obj.sum(5, 3)); } } Output: 8
To view or add a comment, sign in
-
-
📌 Strings, Arrays & split() in Java 🔹 String String is a class used to store a group of characters and is represented in double quotes (" "). 👉 Ways to create String: Using string literal String s = "Hello"; Using new keyword String s = new String("Hello"); 👉 Important points: Strings are immutable (cannot be changed) Stored in String Constant Pool (SCP) Using "new" → stored in heap memory Comparing objects → compares address Default value → null 🔹 String Methods Commonly used methods: length() → returns length of string toUpperCase() → converts to uppercase toLowerCase() → converts to lowercase charAt(index) → returns character equals() → compares two strings contains() → checks substring substring(start, end) → extracts part startsWith() → checks starting value endsWith() → checks ending value trim() → removes spaces 💻 Example: String s = "Hello Java"; System.out.println(s.length()); System.out.println(s.toUpperCase()); System.out.println(s.charAt(1)); 👉 Output: 10 HELLO JAVA e 🔹 split() Method Used to split a string into parts. 💻 Syntax: variable.split(" "); 💻 Example: String s = "Hi This is Java"; String[] words = s.split(" "); 👉 Output: Hi This is Java 🔹 Arrays Arrays are used to store multiple values of the same data type. 👉 Key points: Fixed size Same data type Stored in continuous memory Index starts from 0 💻 Syntax: int[] arr = new int[5]; 👉 Other ways: int[] arr = {1,2,3}; int arr[] = new int[5]; These concepts help in handling text data and storing multiple values efficiently in Java. #Java #CodingJourney #LearnJava #FullStackDeveloper
To view or add a comment, sign in
-
-
What’s ‘Static’ in Java? Why to use it? Static, as in fixed. Applying it to Object-Oriented tech - something that doesn’t change for every object, it’s fixed for all objects. Generally fields are created separately in memory for each instance of a class, i.e. Object variables. But, anything declared using static keyword belongs to the class instead of individual instances (objects). What does it mean? That every object of this class share this same copy of the variable, method, etc. We can apply static keyword with variables, methods, blocks and nested class. The benefit – memory management of course. public class Student{ private String Name; //Object variable private int Age; //Object variable private String StudentId; //Object variable public static int NumberOfStudents = 0; //Class variable public Student(String name, int age, String studentId) { this.Name = name; this.Age = age; this.StudentId = studentId; NumberOfStudents++; //Increase the no of students whenever an object is created. } } The most common example is << public static void main(String args[]) >> declared static because it must be called before any object exists. Making a method static in Java is an important decision. Does it make sense to call a method/variable, even if no object has been constructed yet? If so, it should be static. Static entity, • Will be initialized first, before any class objects are created. • Is accessed directly by the class name and doesn’t need any object. • Can access only static data. It cannot access non-static data (instance variables). • Can call only other static methods and cannot call a non-static method. Caution: Generally, it is bad practice to set the WebDriver instance as static. Instead create a base class that each test classes extend so that each test class has its own instance of WebDriver to be used (this is especially important with parallel execution), then just declare/define your WebDriver variable within the base class.
To view or add a comment, sign in
-
There is no silver bullet when choosing between LinkedList and ArrayList in Java. I’m currently studying DSA for coding interviews, and revisiting the trade-offs between these two classes has been a great refresher. 𝐋𝐢𝐧𝐤𝐞𝐝𝐋𝐢𝐬𝐭 is an implementation of a doubly-linked list. It stores each record in a node consisting of the data and two pointers. • The Trade-off: You can insert or delete records in O(1) time because you just change the pointers to the new address, but finding data takes O(n) due to link traversing. It also uses more memory to store those extra pointers. • Best Use Case: When you need to frequently insert and delete from the beginning or end of a collection. A classic example is building an "Undo" feature where you constantly save and remove the latest edit. 𝐀𝐫𝐫𝐚𝐲𝐋𝐢𝐬𝐭 uses an internal array that the JVM dynamically resizes when needed. The records are stored in contiguous data blocks, providing excellent memory locality and exploiting CPU cache for fast access. • The Trade-off: You get O(1) read access using indexes. However, insertion and deletion can be O(n) in the worst case because the JVM has to shift elements to make room, or when the array has reach its capacity, copy and rewrite the old data to a new allocated array. • Best Use Case: When you need to iterate over large datasets quickly, such as generating a monthly financial report from thousands of transactions. You can read more about them in the official Java 25 docs: 🔗 LinkedList: https://lnkd.in/d_kVgPpW 🔗 ArrayList: https://lnkd.in/dkpzZZxf
To view or add a comment, sign in
-
-
🚀 Java Wrapper Classes & The Mystery of Buffer Caching Many devs get confused when this happens: Integer a = 100; Integer b = 100; System.out.println(a == b); // ✅ true (cached) Integer x = 200; Integer y = 200; System.out.println(x == y); // ❌ false (different objects) 🤔 Why is 100 cached but 200 is not? This behavior occurs because of Integer Caching, a memory optimization technique in Java's wrapper classes. 1. Reference vs. Value Comparison In Java, the == operator behaves differently depending on the data type: Primitives (int): Compares actual numerical values. Objects (Integer): Compares memory addresses (references). It checks if both variables point to the exact same object in memory. 2. The Integer Cache To save memory and improve performance, the Java Virtual Machine (JVM) maintains a cache of Integer objects for frequently used values. The Default Range: Values between -128 and 127 (inclusive) are pre-created and stored in a pool. How it Works: When you assign a value like Integer a = 100, Java uses autoboxing to convert the primitive to an object. Internally, it calls Integer.valueOf(100), which returns a reference to the already existing object in the cache. 3. Why 100 == 100 is True When you declare two Integer variables with the value 100: Both variables are assigned the same reference from the internal cache. Because they point to the exact same object in memory, a == b evaluates to true. 4. Why 200 == 200 is False When you use a value outside the cache range, such as 200: Java must create a new, distinct object for each assignment. Even though their values are the same, these two objects exist at different memory addresses. Because the references are different, x == y evaluates to false. Best Practice To avoid this "trap," always use the .equals() method when comparing Integer objects. This method compares the actual numerical value inside the object rather than its memory location. 💡 Next time someone asks why 200 isn’t cached but 100 is — you know the JVM story behind it 😉
To view or add a comment, sign in
-
Java Program: Write a program to remove duplicates from an array. Core Functionality The program processes an integer array containing several duplicate values (such as 65 and 87). It utilizes a Set data structure to filter out these duplicates and then attempts to sort the result before printing it to the console. Step-by-Step Execution Initialization: An integer array named array is defined with the values {10, 20, 65, 87, 44, 87, 65, 2, 1}. Deduplication: A LinkedHashSet<Integer> is instantiated. A Set is a collection that, by definition, cannot contain duplicate elements. The program iterates through the array using an enhanced for loop. For each number, it checks if the set already contains the value. If not, it adds the value to the set. Note: Since a Set automatically rejects duplicates, the if(!set.contains(num)) check is technically redundant but safe. Sorting: The code calls Arrays.sort(set). Technical Note: In standard Java, Arrays.sort() is designed for arrays, not Collections like a Set. To make this specific code snippet functional in a real environment, the set would typically be converted back into a list or an array before sorting, or a TreeSet would be used to handle sorting automatically. Output: Finally, the program prints the resulting collection to the console. Comparison of Collection Types used Summary of Key Points Purpose: To extract unique elements from a dataset and sort them. Mechanism: Leverages the unique property of the Java Collections Framework (specifically Set) to handle duplicate logic automatically. Result: The original array of 9 elements is reduced to 7 unique elements: [1, 2, 10, 20, 44, 65, 87].
To view or add a comment, sign in
-
-
💡 Why do we need forEach() in Java 8 when we already have loops? Java has always supported iteration using traditional loops. But with Java 8, forEach() was introduced to align with functional programming and stream processing. Let’s break it down 👇 🔹 1. Traditional for Loop for(int i = 0; i < arr.length; i++){ System.out.println(arr[i]); } ✅ Gives full control using index ✅ Supports forward & backward traversal ✅ Easy to skip elements or modify logic ⚠️ Downside: You must manage indexes manually, which can lead to errors like ArrayIndexOutOfBoundsException ------------------------------------------------------------------------------ 🔹 2. Enhanced for-each Loop for(int num : numbers){ System.out.println(num); } ✅ Cleaner and simpler syntax ✅ No need to deal with indexes ⚠️ Limitation: Only forward iteration No direct access to index ------------------------------------------------------------------------------ 🔹 3. Java 8 forEach() (Functional Approach) Arrays.stream(numbers) .forEach(num -> System.out.println(num)); 👉 Even more concise: Arrays.stream(numbers) .forEach(System.out::println); ✅ Encourages functional programming ✅ Works seamlessly with Streams API ✅ More expressive and readable ✅ Can be used with parallel streams for better performance ------------------------------------------------------------------------------ 🔍 What happens internally? forEach() is a default method in the Iterable interface It takes a Consumer functional interface The lambda you provide is executed via: void accept(T t); ------------------------------------------------------------------------------ 🚀 Final Thought While traditional loops are still useful, forEach() brings a declarative and modern way of iterating data — especially when working with streams. #Java #Java8 #Programming #Developers #Coding #FunctionalProgramming
To view or add a comment, sign in
-
Records in Java — Say Goodbye to Boilerplate Code Writing simple data classes in Java used to mean creating: fields constructors getters equals() hashCode() toString() A lot of code… just to store data. With Records (introduced in Java), Java made this much simpler. Instead of writing this: class Person { private final String name; private final int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } } You can simply write: record Person(String name, int age) {} And Java automatically generates: 1. Constructor 2. Getter methods (name(), age()) 3. equals() 4. hashCode() 5. toString() Why Records matter? 1. Less boilerplate code 2. Immutable by default 3. Cleaner and more readable code 4. Perfect for DTOs, API requests/responses, and model classes Example: record Employee(String name, String department, double salary) {} Usage: Employee emp = new Employee("John", "Engineering", 90000); System.out.println(emp.name()); Records become even more powerful with modern Java features like Sealed Classes: sealed interface Shape permits Circle, Rectangle {} record Circle(double radius) implements Shape {} record Rectangle(double length, double width) implements Shape {} Modern Java is getting cleaner, safer, and more expressive. In one line: Records = Less code, more clarity. #Java #Java17 #JavaDeveloper #BackendDevelopment #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
More from this author
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