Finding common elements between two lists using Java Streams can be approached with performance in mind. Consider the following two lists: List<Integer> intList1 = List.of(1, 2, 3, 4, 5, 6); List<Integer> intList2 = List.of(2, 4, 6, 8, 10); Here are three options to find the common elements: **Option 1:** ```java System.out.println(intList1.stream() .filter(intList2::contains) .collect(Collectors.toSet())); ``` This method is straightforward but has a time complexity of O(n * m) because for each element in intList1, the `intList2::contains` checks the entire list. This is not efficient for large lists. **Option 2:** ```java Set<Integer> set2 = new HashSet<>(intList2); System.out.println(intList1.stream() .filter(set2::contains) .collect(Collectors.toSet())); ``` In this approach, the time complexity improves to O(n + m) since the average time for a HashSet lookup is O(1). **Option 3:** ```java Set<Integer> common = new HashSet<>(intList1); System.out.println(common.retainAll(intList2)); ``` This option utilizes a built-in function and also achieves a time complexity of O(n + m), while being simpler in implementation. By considering these options, you can choose the most efficient method for your specific use case.
How to find common elements in two lists with Java Streams
More Relevant Posts
-
In modern Java applications, generating dynamic text is a common need — whether it’s building personalized email content, log messages, SQL queries, or configuration templates. Templating and placehol https://lnkd.in/d8_XFUgg
To view or add a comment, sign in
-
When you code in Java, the appeal of the work lies in the use of Generics. For example, when we have a class : public class Response<T> { private ResponseError error; private T response; private Map<String, Object> additionalProperties; } Now, if we want to use this class as a response for calling an external service, how would we do it? @PostMapping(value = "${feignClients.example-url-address}", produces = "application/json", consumes = "application/json") Response<exampleResponse> getInfo(@Valid @RequestBody exampleRequest request); In this case, if we don't define the response object or exampleResponse properly, we won't be able to map the response returned by the service correctly. The outer Response<> type has a field called response. so Jackson puts this part of the JSON into that field. So, if you define the service response class like this: private ٍExampleError error; private ExampleResponseData response; Therefore you get the error: Unrecognized field "someResponse" Since your API already wraps everything in an "error" and "response" field, you don’t need another Response<> wrapper in your Feign client.If your project uses a global Response<T> wrapper for all Feign clients, then you must change the generic type parameter so it matches the actual JSON structure. The "Unrecognized field" error is quite simple but useful. 🙂 In the comment, share your experiences in this area. 😊 #JSON #JACKSON #GENERICS #JAVA
To view or add a comment, sign in
-
Master the Java String replace() Method: A 2025 Guide with Examples & Use Cases Stop Fumbling with Text! Master the Java String replace() Method Like a Pro Let's be real. As a developer, you spend a ridiculous amount of time dealing with text. Whether it's user input, data from an API, or just generating dynamic messages, strings are the lifeblood of your code. And what's one of the most common things you need to do with text? Change it. Maybe you need to clean up data, censor words, or personalize a message. That's where Java's String.replace() method comes in. It's one of those fundamental tools that seems simple on the surface but has more depth than you might think. In this deep dive, we're not just going to skim the surface. We're going to break down the replace() method so thoroughly that you'll be wielding it with absolute confidence. We'll cover the what, the why, the how, and the "what to watch out for." Buckle up! So, What Exactly is the Java String replace() Method? The key thing to remember is that strings in Java are immutable. This is a fancy way o https://lnkd.in/gd_XWKgK
To view or add a comment, sign in
-
Master the Java String replace() Method: A 2025 Guide with Examples & Use Cases Stop Fumbling with Text! Master the Java String replace() Method Like a Pro Let's be real. As a developer, you spend a ridiculous amount of time dealing with text. Whether it's user input, data from an API, or just generating dynamic messages, strings are the lifeblood of your code. And what's one of the most common things you need to do with text? Change it. Maybe you need to clean up data, censor words, or personalize a message. That's where Java's String.replace() method comes in. It's one of those fundamental tools that seems simple on the surface but has more depth than you might think. In this deep dive, we're not just going to skim the surface. We're going to break down the replace() method so thoroughly that you'll be wielding it with absolute confidence. We'll cover the what, the why, the how, and the "what to watch out for." Buckle up! So, What Exactly is the Java String replace() Method? The key thing to remember is that strings in Java are immutable. This is a fancy way o https://lnkd.in/gd_XWKgK
To view or add a comment, sign in
-
Java Tip of the Day: Using `Optional` for Null-Safe Returns `Optional<T>` is a container object used to contain not-null objects. It helps developers write more robust and readable code by explicitly handling the presence or absence of a value, thereby reducing the chances of `NullPointerException`s. Insight Detail ```java import java.util.Optional; public class UserDataService { public Optional<String> getUserNameById(long id) { // Simulate fetching data from a database if (id == 101) { return Optional.of("Alice Wonderland"); } else if (id == 102) { return Optional.of("Bob The Builder"); } return Optional.empty(); // No user found } public static void main(String[] args) { UserDataService service = new UserDataService(); // Case 1: User found Optional<String> name1 = service.getUserNameById(101); name1.ifPresent(name -> System.out.println("User 101 Name: " + name)); System.out.println("User 101 Name (orElse): " + name1.orElse("Default User")); // Case 2: User not found Optional<String> name2 = service.getUserNameById(999); name2.ifPresent(name -> System.out.println("User 999 Name: " + name)); // This won't print System.out.println("User 999 Name (orElse): " + name2.orElse("User Not Found")); } } ``` Why this matters `Optional` forces you to explicitly consider the null case, making your API contracts clearer and preventing common `NullPointerException`s. This leads to more robust, readable, and maintainable code by eliminating ambiguity about method return values. Let’s #CodeAndGrowTogether with #CodersOutput Follow for job updates and technical insights to keep learning and growing!
To view or add a comment, sign in
-
“Everyone says they know Java Strings… until this happens 👇” What’s the output? String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java"); System.out.println(s1 == s2); System.out.println(s1 == s3); System.out.println(s1.equals(s3)); Most will say: “All true — same value!” But nope ❌ Output: true false true Why? Because "==" compares references (memory location) .equals() compares content (actual string value) s1 and s2 point to the same literal in the String pool, but new String("Java") creates a new object in the heap, so the reference check fails even though the content is identical. Lesson? 👉 Knowing how Java handles memory and strings is what separates a coder from a problem solver.
To view or add a comment, sign in
-
💡Do You Know about Copy Constructor? 👉 A copy constructor in Java is a special constructor that takes another object of the same class as its parameter and copies its values into the new object. Examples: ▪️ Imagine we have a Student object and we want to make a copy of it. ▪️ A copy constructor allows we to clone the object safely and easily. 👉 Key Points: ▪️ A copy constructor takes one argument: an object of the same class. ▪️ It copies each variable from the existing object to the new object. ▪️ Java does not provide a copy constructor by default; we must write it ourself. ▪️ It creates a deep copy for simple types (like int, String), but for objects, we may need to write a custom deep copy if needed. ▪️ The new object and the original are stored in different memory locations. 💡 Why It’s Useful? ▪️ Allows creating a new object with the same data as an existing object. ▪️ Avoids repeating the same assignments manually for every field. ▪️ Keeps your code clean, short, and easy to understand. ▪️ Ensures the new object is separate, so changes to it don’t affect the original. ▪️ Provides a professional design to your class, especially in real-world applications. 💡 Can we overload a copy constructor? ✅ Yes. Like any constructor, we can overload it — but the common pattern is to have one copy constructor taking a single object. ✌ Finally, ✅ A copy constructor is essential for cloning objects in Java. It simplifies the process, ensures data integrity, and maintains clean code structure. ✅ By mastering copy constructors, We're enhancing our ability to write professional, safe, and maintainable Java code. #Java #JavaPrgramming #LearnJava #JavaSpringBoot #CoreJava #OOPS
To view or add a comment, sign in
-
-
In #Java, a class can have a field of the Collection type. When we create a new object of the class, we need to take few extra steps to handle Collection fields in a safe manner. You may say, wait a minute, the elements of my Collection, are immutable objects! Because they are implemented as Java records, or whatever technique you use to implement an immutable class. That simplifies the problem, but doesn't completely eliminate it. And the problem here is that the collection itself may not be an immutable object, what means that other parts of the application can hold the same collection reference and accidentally modify the collection in a way that wasn't expected by our custom class. The solution to this is to create a new reference for the collection and do defensive copy for all the elements. If we are using immutable elements, that solves the second part, we don't need to defensively copy immutable objects because they can't change. Regarding the first part, the quickest solution would be to use 𝐋𝐢𝐬𝐭.𝐜𝐨𝐩𝐲𝐎𝐟() method that will create a new list reference. But if you read the method documentation, you will see that this method will create an unmodifiable list, which doesn't support NULL list elements. So to bulletproof the logic, it's better to first filter out all null elements, and only after that return a new collection instance. If you use Stream API and its toList() method, it will return an unmodifiable list. Below code uses Java record compact constructor to create a new collection reference when instantiating an object:
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