Removing item from generic list java? [closed] - java

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 8 years ago.
Improve this question
I need to remove an item from a generic list in java, but I don't know how to do this. If it was a list of int, I would just set it to zero, if it was strings I would set it to null. How can I do this with a generic list, and I can't use an methods of Arraylist or anything like that, I have to write the method myself.

You can remove an individual object instance with List.remove(Object) or you can remove a specific instance from a specific index with List.remove(int). You can also call Iterator.remove() while you iterate the List. So, for example, to remove every item from a List you could do
Iterator<?> iter = list.iterator();
while (iter.hasNext()) {
iter.remove();
}

I would think that if you are implementing a list yourself you should move all elements after the element you are deleting down one position, set the last one to null, and if you are keeping track of the size of your list, reduce this by one. Something like this
public Object remove(int remove_index){
Object temp = list[remove_index];
for(int i=remove_index;i<size-1;i++){
list[i] = list[i+1];
}
list[--size] = null;
return temp;
}

static <T> List<T> remove(List<? extends T> inputList, int removeIndex)
{
List<T> result = new ArrayList<T>( inputList.size() - 1 );
for (int i = 0 ; i < inputList.size() ; i++)
{
if ( i != removeIndex )
{
result.add( inputList.get(i) );
}
}
return result;
}

Related

Java Remove ArrayList by Value [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 5 years ago.
Improve this question
I have an ArrayList like this:
[{1=R111, 2=Red, 3=50000}, {1=R123, 2=Blue , 3=50000}]
and i want to remove the array by value (R111 or R123).
how to remove the array using array.remove method for array like that?
I've try this link
but it's doesn't work for my problem.
Assuming your ArrayList is this:
List<String[]> arrayList = new ArrayList<>();
arrayList.add(new String[]{"R111","Red","50000"});
arrayList.add(new String[]{"R123","Blue","50000"});
you can do something like:
for (Iterator<String[]> iterator = arrayList.iterator();iterator.hasNext();) {
String[] stringArray = iterator.next();
if("R111".equals(stringArray[0])) {
iterator.remove();
}
}
You can safely remove an element using iterator.remove() while iterating the ArrayList. Also see The collection Interface.
An alternative shorter approach using Streams would be:
Optional<String[]> array = arrayList.stream().filter(a -> "R111".equals(a[0])).findFirst();
array.ifPresent(strings -> arrayList.remove(strings));
Thanks pieter, I used Iterator like this:
for (Iterator<HashMap<String, String>> iterator = RegulerMenu.iterator(); iterator.hasNext();) {
HashMap<String, String> stringArray = iterator.next();
if("R111".equals(stringArray.get("1"))) {
iterator.remove();
}
}
It's work now, Thankyou verymuch.

Removing all values from HashMap but keeping the keys? [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 6 years ago.
Improve this question
I am trying to delete all values associated with all keys in my HashMap, but still keep the keys.
Is the below correct / the most efficient way to do so?
for (Map.Entry<Kennel, List<Dog>> entry : hashMap.entrySet()) {
String key = entry.getKey().getId();
List<Dog> dogList = entry.getValue();
//Loop through the list associated with each key and delete each Dog in the list
for (int i=0; i<dogList.size(); i++){
dogService.delete(dogList.get(i));
dogService.save(dogList.get(i));
}
}
Simpler:
for(dogs : hashMap.values()) {
for(dog : dogs) {
dogService.delete(dog);
dogService.save(dog);
}
dogs.clear();
}
I don't know what you are trying to accomplish here but if you just want the unique keys then probably you should be using a HashSet instead of HashMap.
But, if you want to perform the deletion you can just do the following:
for (Kennel key : hashMap.keySet()) {
hashMap.put(key, null);
}
I have written Kennel key assuming that key of your HashMap is of type Kennel.
You could use at the end:
hashMap.put(entry.getKey(), null);
removing the whole list, but if you want put new dogs into it in the future (as I think you want), and your dog lists are modifiable, the following approach is more memory-friendly:
for (Map.Entry<Kennel, List<Dog>> entry : hashMap.entrySet()) {
String key = entry.getKey().getId();
Iterator<Dog> it = entry.getValue().iterator();
while (it.hasNext()) {
Dog dog = it.next();
dogService.delete(dog);
dogService.save(dog);
it.remove();
}
}
since you avoid allocating new lists in the future. Notice also the usage of it.remove() that allows deletion while iterating

Iterator with compareTo java [closed]

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 7 years ago.
Improve this question
As a general concept, say we have a compareTo method which returns 1, 0 or -1.
How is it possible to use an iterator to find out the maximum value in an array, using the compareTo method?
Simply:
Iterator<E> it = collection.iterator;
E max = null;
while(it.hasNext()) {
if(max == null) {
max = it.next();
} else {
e = it.next();
if(e.compareTo(max) > 0) {
max = e;
}
}
}
If you just want to find the maximum element in an array (without explicitly using the iterator and compareTo), then you can convert your array into a Collection or Stream:
Integer[] objectArray = {3,66,4,22,4};
List<Integer> objectList = Arrays.asList(objectArray);
System.out.println(Collections.max(objectList));
int[] primitiveArray = {3,66,4,22,4};
IntStream intStream = Arrays.stream(primitiveArray);
System.out.println(intStream.max().getAsInt());
Collections.max uses an iterator and compareTo under the hood (as you can see by reading its source code), but the second way doesn't (because it's using primitives).

Arraylist - how to get a specific element/name? [closed]

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 8 years ago.
Improve this question
I've tried to search the WWW but failed to find an answer. Couldn't find one here either.
Here's my question:
How do I get a specific name(element?) from a Customer in an ArrayList?
I'm imagining it looks something like this:
ArrayList<Customer> list = new ArrayList();
String name = list.get(2) // which would return the Customer at 2's place.
But what if I want to search for a customer by name, lets say a customer named Alex? How do I do that?
Bonus question: How do I then delete that customer?
As others have said this isn't all that efficient and a HashMap will give you fast lookup. But if you must iterate over the list you would do it like this:
String targetName = "Jane";
Customer result = null;
for (Customer c : list) {
if (targetName.equals(c.getName())) {
result = c;
break;
}
}
If you need to remove an item from a list while iterating over it you need to use an iterator.
String targetName = "Jane";
List<Customer> list = new ArrayList<Customer>();
Iterator<Customer> iter = list.iterator();
while (iter.hasNext()) {
Customer c = iter.next();
if (targetName.equals(c.getName())) {
iter.remove();
break;
}
}
Your are going to have to iterate through your array using something like this in a function call.
void int HasName(string name){
for(int i=0; i < list.size(); i++) {
String s = list.get(i).getName();
//search the string
if(name.equals(s)) {
return i
}
}
return -1
}
If you really need to search by name consider looking into HashMap.
With an ArrayList, you have to loop... If you can, use a Map (HashMap, TreeMap) to quickly find an element.
This works if you always seek by name, for example. (use name as key of the map)
There isn't a way to explicitly do what you want, unless you want to iterate through the whole collection, comparing the desired name to the current one. If you want this type of functionality, you could try a Map such as HashMap.
Implement equals and hashcode for Customer object. Use customer name attribute for this.
Use ArrayList.indexof to find the index of the element. use the remove method in Arraylist to remove the object by index.

Object conversion [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 9 years ago.
Improve this question
I have list defined as - List iAmAListWithNoGenricType;
Strings are being stored in the list.
I am passing this list to a method which
paramMap = populateMap(list,paramMap);
public Map<Object,Object> populateMap(List list,Map<Object,Object> paramMap){
paramMap.put("key",list);
return paramMap;
Now on doing this hashcodes are being stored in the Map.
key = {#code,#code......}
I tried these :-
List<String> newList = new ArrayList<String>();
for(String item:list){
newList.add(item);
}
and also tried converting a object to string but everything failed.
User iterator as well like this :-
Object element=itr.hasNext();
newList.add((String)element);
Also,
newList.add(item.toString());
But the system crashes.
What is the way out?
First thing, you haven't initialized your list. Secondly, you should provide the exception which you are getting instead of posting "System crashes".
Here, you have got element, which is of type Boolean, as itr.hasNext() returns true OR false based upon if any next element exists in list or not. Then you have used this into sysout where you can get classcastexception. As you can't cast Boolean to String.!
So use hasNext method in this way may help -
while(itr.hasNext()) {
//operation on list like ADD
}
for (Object o : list) {
newList.add((String) o);
}
Note that you shouldn't have a list without a type parameter if at all possible.
In this attempt:
List<String> newList=new ArrayList<String>();
for(String item:list){
newList.add(item);
}
Java seem that the static type of elements of list is Object. You can't assign those to a String variable without a cast, so Java refuses to allow your code.
In this attempt:
Object elemnt=itr.hasNext();
newList.add((String)element);
hasNext doesn't return the next element. It returns true if the list has more elements to iterate over. The boolean it returns gets autoboxed to a Boolean and stored in elemnt, and then the attempt to cast the Boolean to String fails.
In this attempt:
newList.add(item.toString());
toString isn't how you cast something you know is a String to the static type String, but it wouldn't have caused a crash or compile error by itself. You probably had more errors somewhere else.
Object elemnt=itr.hasNext();
newList.add((String)element);
This crashes because Iterator.hasNext() is a boolean. Correct code would be:
while(itr.hasNext())
newList.add((String)itr.next());
Or something like that.
Modify your code as below: No need to pass the map to method, if you want to return the same map from the method.
public Map<Object,Object> populateMap(List list){
Map<Object,Object> paramMap = new HashMap<Object,Object>();
if(list != null & list.size() > 0){
int key = 1;
for(Object obj : list){
paramMap.put(("Key"+key), obj);
key++;
}
}
return paramMap;
}
Call your method like this:
Map<Object,Object> paramMap = populateMap(list);

Categories

Resources