Arraylist - how to get a specific element/name? [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 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.

Related

iterate the List and set the value with data available in another list [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 1 year ago.
Improve this question
I have the below two List objects, i want to iterate the addrMappingList and set the Person to the field by getting the person object from personList.
Below is the sample code.
List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();
Sample AddressMapping class:
class AddressMapping {
private int id;
private Person person;
..
}
Sample Person class:
Class Person{
private int personId;
private String personName;
...
}
I want to iterate the addrList and for each addrList element i want to set the personList element.
Tried the below code:
for(AddressMapping addrMapping : addrMappingList){
for(Person p : personList){
addrMapping.setPerson(p);
}
}
I should not iterate the Person inside the addrMapping as shown in the above code, any inputs would be helpful.
PS: Two list doesn't have any data to compare and set the value.
You only need one iteration to do that. Since you actually need the index, it also means you can use a good old for loop for this:
List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();
for(int i = 0; i < personList.size(); i++) {
addrMappingList.get(i).setPerson(personList.get(i));
}
Of course, since personList and addrMappingList have the same number of elements, this is an option.
UPDATE
If by "with Java8" you mean using a more "modern" syntax, you could also use the following.
List<Person> personList = getPersonList();
List<AddressMapping> addrMappingList = personToAddressMappingList();
IntStream.range(0, personList.size())
.forEach(i -> addrMappingList.get(i).setPerson(personList.get(i)));
With all that, I think the first approach is better because this is a very simple function not worth overcomplicating. I don't really know if there is any performance benefits (And if there are, at what point they are noticeable), but unless it's significant I prefer readability (The KISS principle).
If you mean that the two lists are parallel arrays, and that the first element in one is paired with the first element of the other, etc., then you should not use an foreach-loop. Instead, manage the index explicitly:
if (personList.size() != addrMappingList.size()) throw new IllegalArgumentException();
for (int idx = 0; idx < addrMappingList.size(); ++idx) {
addrMappingList.get(idx).setPerson(personList.get(idx));
}

Implementing a Bag in 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 5 years ago.
Improve this question
I'm implementing a bag of Integers in java and I'm not sure how to do so. I would like to do so with either a HashMap, LinkedHashMap, TreeMap, TreeSet, or HashSet. Some of the things I'd like to do are
Be able to count the number of occurrences of a certain element (So I cannot use a set)
be able to add without the structure immediately deleting duplicate integers
I've tried implementing a map so far but I run into problems when I try to add to the map because I'm trying to implement a bag of integer objects not key value pairs.
public class Bag<Integer> {
private int count = 0;
private HashMap <T, Integer> map;
//class constructor
public Bag(){
this.map = new HashMap <T, Integer>();
}
would a linked hash set be best? I'd like to add duplicate Integers.
If I read your question correctly, you simply want
Map<Integer, Integer> integerBag = new HashMap<>();
Key: represents the different Integers you have in your bag.
Value: represents the count how often the corresponding key was added.
When adding a "new" Integer, you put(newValue, 1) into the map. When the same number comes in, you increase that counter; and decrease on removal.
Beyond that:
without the structure immediately deleting duplicate integers doesn't make much sense. Integers are just numbers; why would you want to remember "6 6 6" ... when you could remember "I got 6 three times" instead?!
Given your comments:
you don't need to change the signature of your method. The compiler generates code to turn primitive types such as int into their big brothers such as Integer automatically. That is called auto-boxing.
but you can also do that manually.
See here:
int intval =5;
Integer asInteger = Integer.valueOf(intval);
if (Integer bag.contains(asInteger)) {
Just use a HashMap. You might want to count how many duplicates you have:
Map<Whatever, Long> bag = new HashMap<>();
To add an element, use the merge method:
bag.merge(someElement, 1, (oldValue, value) -> oldValue + 1);
And to remove an element, you might want to use the computeIfPresent method:
bag.computeIfPresent(someElement, (key, value) -> (value == 1 ? null : value - 1));
Because of your requirement #2, I don't think you can use any collection based on hashing. If you need to retain duplicate Integers, you'll need to use a List.
Adding a new items is easy, just call add() on the list. Finding all items requires a short loop; to count them just call size() on the resulting list.
The code below is not tested.
public class Bag<T> {
private List<T> items = new ArrayList<>();
public void add( T i ) { items.add(i); }
public List<T> findAll( T target ) {
ArrayList<T> retVal = new ArrayList<>();
for( T i : items ) {
if( i.equals(target) )
retVal.add( i );
}
return retVal;
}
}

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

Removing item from generic list java? [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 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;
}

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