📘 Java Learning – Collections Framework (Part 4: Set & Its Implementations) 🚀 Continuing my Core Java Collections journey, this time I focused on Set-based collections — where uniqueness and ordering rules really matter. Here’s a crisp breakdown 👇 2️⃣ Set Interface • Child interface of Collection • Duplicates are NOT allowed • Insertion order is NOT preserved • No new methods — only Collection methods are used Use Set when uniqueness is the top priority. 🔰 HashSet (C) • Underlying data structure: Hash Table • No duplicates • No insertion order • Allows one null • Heterogeneous objects supported • Best choice for fast search operations 📌 Important behavior Trying to add a duplicate doesn’t throw an error — add() simply returns false. 🧪 Short Example: HashSet hs = new HashSet(); hs.add("Java"); hs.add("Python"); hs.add("Java"); // ignored hs.add(null); System.out.println(hs); 🔰 LinkedHashSet (C) • Child class of HashSet • Underlying structure: HashTable + LinkedList • Insertion order is preserved • Still no duplicates 📌 Common use case Used in cache-like applications where: • Duplicates are not allowed • Insertion order must be maintained 🧪 Short Example: LinkedHashSet lhs = new LinkedHashSet(); lhs.add("A"); lhs.add("B"); lhs.add("C"); System.out.println(lhs); // [A, B, C] 🔰 SortedSet (I) • Child interface of Set • Stores elements in a sorted order • Sorting can be: • Natural ordering • Custom ordering (Comparator) 📌 Useful methods: • first(), last() • headSet(), tailSet(), subSet() • comparator() 📌 Natural sorting: • Numbers → Ascending order • Strings/Characters → Alphabetical order ⭐ Key Takeaway • HashSet → Fast search, no order • LinkedHashSet → Order + uniqueness • SortedSet → Ordered & structured data Choosing the right Set implementation is a design decision, not just an API choice 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #Set #HashSet #LinkedHashSet #SortedSet #JavaCollections #LearningJourney
Java Set Implementations: HashSet, LinkedHashSet, SortedSet
More Relevant Posts
-
📘 Java Learning – Collections Framework (Part 6: Map Interface & HashMap) 🗺️🚀 Continuing my Core Java Collections journey, today I started exploring Map, which stores data as key–value pairs. 🔰 Map Interface • Used to represent data as key–value pairs • Both keys and values are objects • Duplicate keys not allowed, values can be duplicated • Each key–value pair is called an Entry • Map is NOT a child of Collection 📌 Difference • Collection → group of individual objects • Map → group of key–value pairs Example: 101 → "Java" (Entry) 101 = key, Java = value 🔰 Important Map Methods • put(key, value) – adds / replaces value • get(key) • remove(key) • containsKey(), containsValue() • size(), isEmpty(), clear() 🔰 Collection Views of Map • keySet() → Set of keys • values() → Collection of values • entrySet() → Set of entries 🔰 Map.Entry Interface • Each key–value pair is an Entry • Entry exists only inside Map Key methods: • getKey() • getValue() • setValue() 🔰 HashMap (C) • Underlying data structure: Hash Table • No duplicate keys, values can repeat • Insertion order not preserved • One null key allowed, multiple null values allowed • Not synchronized → not thread-safe 🧪 Short Example HashMap m = new HashMap(); m.put(101, "Java"); m.put(102, "Python"); m.put(103, "Programming"); m.put(102, "Spring"); // replaces value System.out.println(m); Set s = m.keySet(); System.out.println(s); // [101, 102, 103] Collection c = m.values(); System.out.println(c); // [Java, Spring, Programming] Set s1 = m.entrySet(); Iterator itr = s1.iterator(); while (itr.hasNext()) { Map.Entry m1 = (Map.Entry) itr.next(); if (m1.getKey().equals(102)) { m1.setValue("Python"); } } System.out.println(m); // {101=Java, 102=Python, 103=Programming} ⭐ Key Takeaway • Map is for relationships (key → value) • HashMap is fast but not thread-safe Building strong Java fundamentals, one Map at a time ☕💻 #Java #CoreJava #CollectionsFramework #Map #HashMap #JavaCollections #LearningJourney
To view or add a comment, sign in
-
🚀 Day 124 of My Java Learning Journey Hi Guys, Today I practiced an important string logical problem — 👉 Finding the occurrence of each character in a String (including spaces) using Java Streams. This type of logic is very common in interviews and improves your understanding of Streams and Collections. ------------------------------------------------------------------------------------------- 💻 Code: -------------> import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class OccurrenceAndNonRepeatingChar { public static void main(String[] args) { String name = "yuvraj singh kushwah"; // Occurrence of all character with spaces Map<Character, Long> charCount = name.chars() .mapToObj(x -> (char) x) .collect(Collectors.groupingBy( Function.identity(), Collectors.counting() )); System.out.println("Occurrence of all characters with spaces: " + charCount); } } ------------------------------------------------------------------------------------------- 🖥 Output: -------------> Occurrence of all characters with spaces: { =2, a=2, g=1, h=2, i=1, j=1, k=1, n=1, r=1, s=2, u=2, v=1, w=1} 🔎 Output Explanation: • Space " " is counted → appears 2 times • Characters like g, i, j, k appear only 1 time • Characters like a, s, u appear 2 times Since we didn’t remove spaces, they are treated like normal characters. ⭐ Important Concept: ✔ chars() → Converts String into IntStream ✔ mapToObj() → Converts int to Character ✔ groupingBy() → Groups identical characters ✔ counting() → Counts frequency This is a clean Java 8+ approach instead of manually using loops and HashMap. 💡 Important Tip: If you don’t want to count spaces, add: .filter(ch -> ch != ' ') before collect(). 🔥 Why This Is Important? ✔ Frequently asked in interviews ✔ Builds strong Stream knowledge ✔ Improves logical thinking ✔ Real-world text processing use case Consistency > Motivation 💪 Day 124 done ✅ What should I practice tomorrow — more Stream problems or interview-based tricky logic? #Java #JavaDeveloper #JavaStreams #CodingPractice #ProblemSolving #InterviewPreparation #DevOps #LearningInPublic #124day #CodeWithYuvi
To view or add a comment, sign in
-
-
🚀 Day 127 of My Java Learning Journey 🤩 Hi Friends, Today I learned how to join two lists using Stream API in Java in a clean and modern way. Instead of using loops, we can use Stream.concat() to combine two lists easily. ------------------------------------------------------------------------------------------- 💻 Code ------------> import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class JoinTwoList { public static void main(String[] args) { List<Integer> list1 = List.of(1, 2, 3); List<Integer> list2 = List.of(4, 5, 6); List<Integer> joinList = Stream .concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); System.out.println("Lists are Joined: " + joinList); } } ------------------------------------------------------------------------------------------- 🖥️ Output Lists are Joined: [1, 2, 3, 4, 5, 6] 🔎 Output Explanation list1.stream() converts first list into stream list2.stream() converts second list into stream Stream.concat() merges both streams Collectors.toList() converts the combined stream back into a list So both lists are joined into a single list. 📌 Important Concept 👉 Stream.concat(Stream s1, Stream s2) It is used to combine two streams into one stream. This method is very useful when working with collections in a functional programming style. 💡 Important Tip List.of() creates an immutable list. You cannot modify it (add/remove elements). If you need a modifiable list, wrap it like this: new ArrayList<>(List.of(1,2,3)); 🤔 Have You Tried This? Do you prefer: Using loops to join lists? Or using Stream API? Let me know your approach in the comments 👇 I am consistently improving my Java skills step by step. If you are also learning Java, let’s grow together 💪 #Java #JavaDeveloper #StreamAPI #Programming #CodingJourney #DevOps #BackendDevelopment #LearningEveryday #day127 #codewithyuvi #Logicalworld
To view or add a comment, sign in
-
-
Hello everyone! 👋 Day 5 of my deep dive into core Java fundamentals! ☕ Today, I explored Type Conversions, specifically answering a crucial question: What is the actual difference between Implicit and Explicit conversions in Java? 🤔 If you think of computer memory as physical boxes, it makes perfect sense! Here is how Java handles moving data between different sized containers: 🟢 1. Implicit Conversion (The Automatic Upgrade) This is also known as a "Widening Conversion". It happens when you move data from a smaller data type (like an 8-bit byte) into a wider/larger data type (like a 32-bit int). Because what fits in a small box will easily fit into a massive box, Java does this completely automatically. You just write int i = b; and the compiler handles it behind the scenes without complaining. 🔴 2. Explicit Conversion (The Manual Override) This is known as a "Narrowing Conversion". This happens when you try to go backwards—stuffing a large container into a smaller one. For example, trying to put a 32-bit int into an 8-bit byte. If you try to do this automatically, Java will throw a compile-time error. Why? Because the compiler is terrified that your data will get chopped off (truncated) during the squeeze! To make it happen, you have to use Type Casting. You have to manually write the target type in brackets, like b = (byte) i;, to explicitly tell Java: "I know the risks, do it anyway!". 🧠 The "Under the Hood" Mindblower: I ran an experiment today: what actually happens if you cast a massive int of 300 into a tiny byte container? Since a byte can only hold up to 127, it obviously overflows. But it doesn't crash! Instead, Java looks at the 32-bit binary representation of 300 and literally chops off the extra bits, keeping only the 8 bits that fit. A massive shortcut I learned: To figure out what number you will end up with, you can just take your number and use the modulo operator against the maximum range of a byte (256). So, 300 % 256 means our new byte will store exactly 44! Understanding how the JVM aggressively protects our memory from data loss makes its strict rules feel so much more logical. 🛡️ #Java #SoftwareEngineering #TypeCasting #TechFundamentals #StudentDeveloper #InterviewPrep #CodingJourney
To view or add a comment, sign in
-
-
🚀 Day 128 of My Java Learning Journey 😆 --- Hi Friends, Today I practiced a simple but powerful logical program using Java 8 Streams — calculating the sum of squares of array elements 💡 Instead of using a traditional loop, I used map() and sum() to make the code clean and readable. ------------------------------------------------------------------------------------------- 💻 Code: ------------> import java.util.Arrays; public class ArraySquareSumByJava8 { public static void main(String[] args) { int[] a = {3, 5, 7, 6, 8}; int sumOfSquares = Arrays.stream(a) .map(y -> y * y) .sum(); System.out.println("Sum of all array squares: " + sumOfSquares); } } ------------------------------------------------------------------------------------------- 🖥 Output: -------------> Sum of all array squares: 183 📖 Output Explanation: Each number in the array is squared: 3² = 9 5² = 25 7² = 49 6² = 36 8² = 64 Then all squared values are added: 9 + 25 + 49 + 36 + 64 = 183 🔎 Important Concept: ✅ Arrays.stream() converts array into a Stream ✅ map() transforms each element ✅ y -> y * y is a Lambda Expression ✅ sum() adds all elements of IntStream Java 8 Streams help us write cleaner and more functional-style code. 💡 Important Tip: When working with int[], Java automatically creates an IntStream, so we can directly use .sum() without extra conversion. Streams make code: ✔ Shorter ✔ More readable ✔ More expressive Are you using Java 8 Streams in your projects? Or still comfortable with traditional loops? 🤔 Let’s grow together 🚀 #Java #JavaLearning #JavaDeveloper #Java8 #Streams #LambdaExpression #CodingJourney #BackendDeveloper #DevOps #100DaysOfCode #CodeWithYuvi #LogicallyJourney #day128
To view or add a comment, sign in
-
-
Why Java Is Not a Pure Object-Oriented Language A pure object-oriented programming language is one where everything in the program is treated as an object. In such languages, even basic values like numbers, characters, and boolean values are represented as objects. There are no primitive data types. javava is a language that embraces many object-oriented concepts, yet it does not fully qualify as a purely object-oriented language. Here are the key reasons why: 1. Presence of Primitive Data Types Java includes several primitive data types, such as: - int - float - double - char - boolean - long - short - byte These types are not objects, which contradicts the principle that all values in a program should be objects. For example, in the code snippet below, `a` is a primitive value, not an object: ```java int a = 5; System.out.println(a); ``` In contrast, languages like Smalltalk treat even numbers and boolean values as objects. 2. Use of the static Keyword Java permits the declaration of methods and variables using the static keyword. Static members are associated with the class itself rather than with an instance of the class, allowing access without creating an object. This undermines the principle that all operations should occur through objects. For instance: ```java class Test { static int count = 0; static void show() { System.out.println("Hello"); } } ``` In this example, the method `show()` can be called without instantiating an object. 3. Wrapper Classes and Primitive Conversion Java offers wrapper classes such as: - Integer - Float - Double - Character - Boolean These classes enable primitive values to be treated as objects. However, Java still relies on primitive types through mechanisms like autoboxing and unboxing. For example: ```java public class BoxingExample { public static void main(String[] args) { Integer i = new Integer(10); Integer j = new Integer(20); Integer k = new Integer(i.intValue() + j.intValue()); System.out.println("Output: " + k); } } ``` In this case, primitive values #ProgrammingConcepts #SoftwareEngineering #Coding #BackendDevelopment #JavaInterview #TechLearning #ProgrammingEducation #CodeNewbie #DeveloperLife #ComputerScience #ProgrammingTips #JavaConcepts
To view or add a comment, sign in
-
-
📘 Java Learning – Collections Framework (Part 8: SortedMap, TreeMap, Hashtable & Properties) 🗺️🚀 Continuing my Java Collections journey, today I explored Map implementations where ordering, synchronization, and configuration matter. 🔰 SortedMap (I) • Child interface of Map • Stores entries in sorted order of keys (not values) • Sorting can be: • Natural order • Custom order (Comparator) 📌 Key methods: • firstKey(), lastKey() • headMap(), tailMap(), subMap() • comparator() 🔰 TreeMap (C) • Underlying data structure: Red-Black Tree • Entries sorted based on keys • Duplicate keys ❌, duplicate values ✅ • Values can be heterogeneous & non-comparable 📌 Key rules: • Natural sorting → keys must be homogeneous & Comparable • Custom sorting → handled by Comparator 📌 Null behavior: • modern Java, TreeMap does NOT allow null keys • After that → NullPointerException • Null values allowed anytime 📌 Constructors: TreeMap t1 = new TreeMap(); // Natural sorting TreeMap t2 = new TreeMap(Comparator c); // Custom sorting TreeMap t3 = new TreeMap(Map m); TreeMap t4 = new TreeMap(SortedMap m); 🧪 Short Example: TreeMap tm = new TreeMap(); tm.put(3, "Java"); tm.put(1, "Spring"); tm.put(2, "Boot"); tm.put("1", "Program") //ClassCastException tm.put(null, "Demo") // NullPointerException System.out.println(tm); // {1=Spring, 2=Boot, 3=Java} 🔰 Hashtable (C) • Legacy Map class • Fully synchronized → thread-safe • No null key or null value allowed • Slower due to synchronization 📌 Constructors: Hashtable h1 = new Hashtable(); Hashtable h2 = new Hashtable(int capacity); Hashtable h3 = new Hashtable(int capacity, float loadFactor); Hashtable h4 = new Hashtable(Map m); 🧪 Short Example: Hashtable ht = new Hashtable(); ht.put(1, "Java"); ht.put(2, "Spring"); System.out.println(ht); 🔰 Properties (C) • Child class of Hashtable • Used for external configuration • Keys and values must be String • Common use: DB URL, username, password, config values 📌 Advantage: • Change configuration without recompiling code • Only redeployment needed → minimal business impact 📌 Constructor: Properties p = new Properties(); 📌 Important methods: • getProperty() • setProperty() • load(), store() 🧪 Short Example: Properties p = new Properties(); p.setProperty("user", "admin"); p.setProperty("url", "localhost"); System.out.println(p.getProperty("user")); ⭐ Key Takeaways • SortedMap → Sorted keys • TreeMap → Sorted + navigable Map • Hashtable → Thread-safe legacy Map • Properties → Externalized configuration Understanding Maps deeply helps build scalable, configurable, and maintainable Java applications 💡 Building strong Java fundamentals, one collection at a time ☕💻 #Java #CoreJava #CollectionsFramework #SortedMap #TreeMap #Hashtable #Properties #JavaCollections #LearningJourney
To view or add a comment, sign in
-
🚀 TAP Academy – Day 15 | Introduction to Strings in Java ☕ Today’s concept is one of the most important topics because nearly 70% of real-world data is handled in String format such as names, emails, passwords, addresses, etc. 📌 What is a String? A String is a sequence of characters enclosed within double quotation marks (" "). Ex: String name = "Java"; String email = "student@gmail.com"; 👉 In Java, String is not a primitive data type 📌 Strings are Objects in Java Here, the class name is String 📌 Types of Strings Strings are divided into two types: 1️⃣ Immutable String Immutable means cannot be changed after creation. Ex:(real world) Date of Birth Gender ID number In Java: String s = "Java"; s.concat(" Programming"); System.out.println(s); output: Java Explanation: The original string is NOT changed A new object is created instead 2️⃣ Mutable String Mutable means can be changed after creation. In Java, mutable strings are created using: StringBuilder StringBuffer Example: StringBuilder sb = new StringBuilder("Java"); sb.append(" Programming"); System.out.println(sb); output: Java Programming 📌 3 Ways to Create Immutable Strings ✅Method 1: Using new keyword 🖋️Object is created in Heap memory 🖋️Duplicate objects are allowed 🖋️Creates a new object every time Ex: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2); // false Because both have different memory locations. ✅Method 2: Without using new keyword 🖋️Stored in String Constant Pool (SCP) inside heap 🖋️Duplicate objects are NOT allowed 🖋️Memory efficient Ex: String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true Because both refer to same memory location. ✅Method 3: Using Character Array char[] ch = {'J','a','v','a'}; String s = new String(ch); System.out.println(s); Output:Java 👉Converts character array into String object 📌 String Comparison Methods 1️⃣ Using == operator Compares reference (memory address) String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2); // true 2️⃣ Using equals() method Compares values String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1.equals(s2)); // true 3️⃣ Using compareTo() method Compares character by character String s1 = "Java"; String s2 = "Jaya"; System.out.println(s1.compareTo(s2)); Output:-21 4️⃣ Using equalsIgnoreCase() method Compares values ignoring case String s1 = "JAVA"; String s2 = "java"; System.out.println(s1.equalsIgnoreCase(s2)); Output:true 📌 Key Summary Points ✅ String = Collection of characters ✅ == compares address ✅ equals() compares values ✅ compareTo() compares character by character ✅ equalsIgnoreCase() ignores case 📌 Real-World Importance Strings are used everywhere: Login systems Emails Banking systems Student records Web applications Without Strings, real-world software cannot exist. 💼#TAP Academy #Java #String #JavaProgramming #LearningJourney #SoftwareDevelopment #JavaDeveloper #Coding
To view or add a comment, sign in
-
-
Hey everyone! 👋 Day 12 of revising my core Java fundamentals! ☕ Today, I explored Functions and tackled a core concept that makes our code so much cleaner: Method Overloading. Imagine you write a simple function to add two numbers, like sum(int a, int b). But later in your program, you realize you also need to add three numbers together. Do you have to create a clunky, brand-new name like sumTwo(int a, int b, int c)? Nope! Java allows us to reuse the exact same function name! We can simply create another function named sum(int a, int b, int c). But this leads to a brilliant "under the hood" interview question... 🤔 ❓ The Interview Question: If multiple functions share the exact same name, how does the Java compiler know which one to execute when you call it? 💡 The Answer: The compiler doesn't just look at the name; it looks at the data you are giving it! To successfully "overload" a function without causing errors, you must change the parameters in at least one of three ways: 1️⃣ Change the Number of Parameters: One version takes 2 arguments, another takes 3. 2️⃣ Change the Data Type of Parameters: One version takes int, another takes double. 3️⃣ Change the Order of Parameters: One version takes (String name, int age), while another takes (int age, String name). 🚨 𝗧𝗵𝗲 𝗨𝗹𝘁𝗶𝗺𝗮𝘁𝗲 "𝗚𝗼𝘁𝗰𝗵𝗮" 𝗧𝗿𝗮𝗽: An interviewer will absolutely try to trick you by asking: "Can I overload a function by keeping the exact same parameters, but just changing the Return Type (like making one return an int and one return void)?" The answer is an absolute 𝗡𝗢! 🛑 If you try this, Java will instantly throw a compile-time "Duplicate Method" error. Why? Because when we call a function in Java, we aren't strictly forced to catch or store its returned value in a variable. If you simply write fun(); in your code, the compiler will be completely confused. It will panic, saying: "I don't know if you wanted me to execute the version that returns nothing (void) or the version that returns an integer (int), because you aren't doing anything with the answer!". To protect you from this ambiguity, the compiler simply blocks you from doing it. Understanding why the compiler restricts us makes these strict rules feel so much more logical! 🛡️ #Java #SoftwareEngineering #TechFundamentals #StudentDeveloper #ComputerScience #InterviewPrep #CodingJourney #Functions
To view or add a comment, sign in
-
Most Java beginners think a variable is "just a box that stores data." But there's SO much more happening under the hood. 🧵 --- When you run a Java program, the JVM carves out a region in RAM called the JRE — divided into 4 segments: 📦 Code Segment → your bytecode lives here 🔵 Static Segment → static variables 🟢 Heap Segment → objects & instance variables 🟡 Stack Segment → local variables & method calls Every variable you declare lands in one of these. Knowing WHERE matters. --- There are 2 types of variables in Java: 🔷 INSTANCE VARIABLES → Declared inside a class, outside any method → Memory allocated in the HEAP → JVM auto-assigns default values (0, false, null) → Each object gets its own copy → Lives as long as the object lives 🔶 LOCAL VARIABLES → Declared inside a method → Memory allocated in the STACK → NO default values — must initialize before use → Temporary — dies when the method exits One rule that catches every beginner: Local variables have NO default values. Use without initializing = compiler error. Every time. --- Now the concept that separates beginners from intermediate devs 👇 PASS BY VALUE vs PASS BY REFERENCE 📋 Pass by Value: When you do b = a → Java COPIES the value. Change b later? a is untouched. Always. int a = 1000; b = a; b = 2000; → a is still 1000. 🔗 Pass by Reference: When you assign objects → Java copies the ADDRESS (reference). Both variables now point to the SAME object in memory. Change via b? a sees it too. Same object. Same heap address. Car a = new Car(); // address: 1000 Car b = a; // b also points to 1000 b.name = "KIA"; // a.name is now "KIA" too 🤯 This is why Java strings and arrays behave "unexpectedly" for beginners. --- Quick Reference: Feature → Local vs Instance Definition → inside method vs inside class Scope → method only vs entire class Initialization → manual vs JVM default Memory → Stack vs Heap Lifetime → method ends vs object exists --- The moment you understand Stack vs Heap + Pass by Value vs Reference — Java starts making sense at a deeper level. Save this. Revisit it when debugging weird variable behavior. 🔖 #Java #Programming #LearnToCode #JavaDeveloper #OOP #CodingTips #ComputerScience #Upskill #Tech #SoftwareEngineering
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