How to delete particular List object in Java? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a list of around 100,000 employees in Java. Now I want to delete a particular employee object from list quickly. What are the possible ways to do it without iterating the whole list?
(If I iterate each object, compare the details then delete: this scenario takes lot of time)

You need a means of find the object quickly. You could
have an ArrayList sorted and then perform a binary search with Collections.binarySearch O(log N) Note: actually removing an element from an ArrayList is O(n) While LinkedList as O(1) for remove, a binary search on it would be pointless i.e. much slower than O(N)
you could have a hash Set of Employee instead and removal would be O(1) amortised. You could use a LinkedHashSet if you would like to preserve some order such as order of insertion.
you could make the object mutable and have a field like enabled which you set to false instead of actually removing it. You could remove it later as a batch job at some time (overnight or on the weekend)

Now I want to delete a particular employee object from list ...
You can just use List.remove to do this
... quickly
In practice, even though removing the item might be an O(1) operation, iterating over the full length of the list is O(n), and is, as you susepcted, not very fast.
I feel that your problem would better be served by the power of a hashmap. This has constant lookup and removal time. The LinkedHashMap class might suit your needs. It maintains insertion order the same way a linked list does, but it also has constant time insertion and deletion.

Related

Interview Question - Data structure performing CRUD operation in O(1) time and maintaining insertion order [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 months ago.
Improve this question
Recently I have attended an interview as backend developer, and I've been asked one the following question:
Design a data structure that can perform insert, update, remove, and
contains operation in O(1) time complexity.
It should allay printing all the elements in O(n) time maintaining the insertion order of
elements.
Can someone please explain which data structure we can use and how that data structure allows to achieve the required O(1) time complexity?
It seems like your interviewer was talking about a composite data structure which combines a Linked list and a Hash table.
And JDK offers and implementation of such data structure in the form of LinkedHashMap, which is basically a combination of a HashMap and a LinkedList. It's methods almost as fast as HashMap's ones.
LinkedHashMap capable to perform these operations in amortized O(1) time (only if the Key has a proper hash-function, the worst case would be O(n)):
insertion via put(key, value);
containsKey(key) check;
updating the value of via replace(key, value) and replace(key, oldValue, newValue);
retrieve the values with get(key);
And owing to a LinkedList maintained under the hood is, LinkedHashMap can can track the insertion order of entries (updating the value of an existing entry has no impact on the order).
Here's a quote from the documentation:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

is there a way to have a "main" arraylist? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Let's say I have
ArrayList<Citizen> citizen1 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen2 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen3 = new ArrayList<Citizen>();
is it possible to have an arraylist which compromise them all?
List<List<Citizen>> mainList= new ArrayList<>();
You can go with List of List.
Also need to consider below points.
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
You can have a List of Lists of Citizen, like this: List<List<Citizen>>= new ArrayList<>();
You can use the addAll() methods of List and Collection to add to one List all the elements of another list.
If using at least Java 8, you can do various things using the Streams API: Stream.of(), Stream.concat(), and maybe others.

Why doesn't LinkedHashSet implement List? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
To my understanding, a List is an ordered collection of items. And a Set is a collection of unique items.
Now my question is, why does LinkedHashSet, which describes an ordered collection of unique items, implement the Set interface (=> unique), but not the List interface (=> ordered)?
One possible argument is that List is intended for random access datastructures, but that would be invalidated by the fact that LinkedList doesn't have "true" random access either. In fact, LinkedHashSet is backed by an internal linked list. Also the documentation for List says otherwise:
Note that these [positional index] operations may execute in time proportional to the index value for some implementations.
If it implemented a List you would be able to use it as a List:
List list = new LinkedHashSet();
This might lead to issues with duplicates which don't appear in Set but are allowed in List.
In other words, you shouldn't declare that something is a List when it doesn't allow duplicates even if it holds the order and allows adding, getting, removing and checking the size.
Unlike sets, lists typically allow duplicate elements
--List documentation
because LinkHashSet is class which implements set interface . List and Set has its own functionality List allowed duplicates while set do not allowed duplicates but if you want linear order insertion in a HastSet then LinkedHashSet is used with no duplicates in itself ..
Set s = new LinkedHashSet();
is the implementation of a set in which insertion order is preserved and duplicates do not allowed..

Java List.add() and Map.put() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Working with Lists and Maps, I started thinking, why Map method for adding Object is called put and for List it is add?
It is just developers will, or there was something under naming those methods different.
May be the methods names let the developer know while adding to Map/List what kind of data structure he is working with?
Or those names describes the way they works?
The difference is :
.add() means to insert something at the end or wherever you want to(you know where to add) whereas
.put() means to add an element wherever it needs to be placed, not necessarily at the end of the Map, because it all depends on the Key to be inserted (you don't know where to add).
To me, it has some cause.
After all, List is a dynamic array, which internally consists a logical index where we are adding.
And map internally carry a bucket of key and value pair. So kind of we are putting something into the bucket.
It can be stated as so because to get a clear understanding.
As java is a 3rd level human understandable language this also can state as a simple English for better understanding.
Collection#add() can be seen that you add your value to a pool of something (an implementation of Collection<E> defines what pool actually is).
Whereas with Map#put() you associate your value with the key which potentially already had a value associated with it.
Add will always add an entry to the end of a list.
Put injects an entry into the map if the key does not already exist; if the key already exists, the value is updated.
Thus the operations are different. On some level, the authors of the API have to make decisions that balance out various concerns. Add to a set has some aspects of add to a list and put to a map, in that adding an "equal" entry has no effect.
For this you should just read the Java docs for add and put.
They are 2 different function, that take completely incompatible inputs, and return completely incompatible values. They are 2 completely separate and distinct functions that behave completely differently (other than they both are for adding elements to a collection (the concept, not interface. As map doesn't implement that interface)).
From the docs
PUT
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
ADD
Appends the specified element to the end of this list (optional operation).
Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.
List :- If i say i'm adding some items to the some Container ill say that i have added the items to the container.Here we are more concentrate on the new item Addition to the existing container or List (in java).
Map :- If i want to put some of the things to the some locker or my computer which is already having the things which i dont care about i just have to put not add.
Here we are concentrate to addition of new data to the locker or Map (in java) regardless of existing the thing.
Real time example:- you add sugar to the tea keeping in mind the amount which is already their.you put your cloths to the Clothing Store regarding their exist any cloths or not.
In java side :-
if you list is like this :-
List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
list.add("perl");
list.add("c");
list.add("lisp");
list.add("c#");
and you want to add something to the list you have to care about the existing thing because if it is list it will add duplicate and if set then don't duplicate.
If you create a Map.
Map<String, Object> foodData = new HashMap<String, Object>();
foodData.put("penguin", 1);
foodData.put("flamingo", 2);
and again you are adding something foodData.put("penguin", 3); you don't have to worry about adding and update the data internally.
I think if you get into etymology we can only guess that since when you place a value into a list you always increase the list length, however if you put the value into a map you would not necessary increase the number of map entries (if the key already exists)

ArrayMap versus HashMap [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
what is the main difference with org.apache.myfaces.trinidad.util.ArrayMap and java.util.HashMap?
Is ArrayMap is thread safe?
In the documentation it is mentioned that Array is best in performance wise.
I don't want to use hashmap or concurrent hashmap. I want to try other like below. which one is best alternative If I consider Thread safety and performance?
ArrayMap<String,String> var= new ArrayMap<String,String>();
HashMap uses an array underneath so it can never be faster than using an array correctly.
Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.The reason your array is so slow is due to the equals comparisons, not the array access itself.
An ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.
List:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background. You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarantee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).
When to use Arrays?
Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.
Sometimes, it may be best to use a combination of the above approaches. For example, you could use a ArrayList of HashMap to suit a particular need.

Categories