I want to display the list of items that i have deleted so far (JAVA). I'm using database as mysql. I'm giving a button in UI on clicking it web service will called and should display the deleted entry. I tried this:
for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
String a = iter.next();
if (...) {
iter.remove();
}
}
You can store all the removed items in a data structure like linked list which is appropriate for appending new items and you don't need to consist memory to it when you define it.
List<String> listOfRemovedItems = new LinkedList<>();
Iterator iterator = originalList.iterator();
while (iterator.hasNext()) {
String s = iterator.next().toString();
if ("meets your condition") {
listOfRemovedItems.add(s);
iterator.remove();
}
}
I added one extra column in table as Flag. Now when user delete it flag is to 1 otherwise it is false.
Related
Rocket class contains: canCarry(Item item)>checks if this item can be carried/ carry updates the weight with total weight.
U2 class is child of Rocket contains: currentweight, maxWeight=18 tons
Item class contains: name to be shipped & weight.
In the method loadU2 I am trying to access a list of items and adding it into one rocket until maxWeight of that rocket is reached . For example I have 216 tons of items to carry returning a list of 12 ships.
It throws me java.lang.IllegalStateException error in the line iterator.remove(). I do not know how to go about it, but it looks like it is not allowing me to remove the items while iterating.
public ArrayList<Rocket> loadU2(ArrayList<Item> loadItems){
//list of ships
ArrayList<Rocket> U2Ships = new ArrayList<Rocket>();
for(Iterator<Item> iterator = loadItems.iterator(); iterator.hasNext();) {
//create a new ship
Rocket tempShip = new U2();
Item tempItem = iterator.next();
//loop over items check if it can be filled then remove the item that was filled.
while(tempShip.currentWeight<tempShip.weightLimit) {
if(tempShip.canCarry(tempItem)){
tempShip.carry(tempItem);
iterator.remove();
}
}
U2Ships.add(tempShip);
}
return U2Ships;
}
Exception in thread "main" java.lang.IllegalStateException
at java.base/java.util.ArrayList$Itr.remove(ArrayList.java:980)
at Simulation.loadU1(Simulation.java:35)
at Main.main(Main.java:14)
Simplified example of what the code is doing:
Assuming maxWeight for each ship = 11 tons
ArrayList loadItems = [3,5,5,8,1,2,3,5] tons
- Ship[1]=[3,5,1,2]
- new list to iterate over >> [5,8,3,5]
- Ship[2]=[5,3]
- new list to iterate over >> [8,5]
- Ship[3]=[8]
- new list to iterate over >> [5]
- Ship[4]=[5]
Please, rewrite your code by creating new ArrayList, instead of changing the existing list inside its own iterator:
public ArrayList<Rocket> loadU2(ArrayList<Item> loadItems){
//list of ships
ArrayList<Rocket> U2Ships = new ArrayList<Rocket>();
ArrayList<Item> updatedLoadItems = new ArrayList<Item>();
for(Iterator<Item> iterator = loadItems.iterator(); iterator.hasNext();) {
//create a new ship
Rocket tempShip = new U2();
Item tempItem = iterator.next();
//loop over items check if it can be filled then only leave the load item that was not fully filled.
boolean addLoadItem = true;
while(tempShip.currentWeight<tempShip.weightLimit) {
if(tempShip.canCarry(tempItem)){
tempShip.carry(tempItem);
addLoadItem = false;
}
}
if (addLoadItem) {
updatedLoadItems.add(tempItem);
};
U2Ships.add(tempShip);
}
loadItems.removeAll();
loadItems.addAll(updatedLoadItems);
return U2Ships;
}
This is not the best solution, but to provide a better solution, you need to change the signature of public ArrayList<Rocket> loadU2(ArrayList<Item> loadItems)
You can try to improve your code by refactoring it.
Hint: right now your loadU2 method tries to do both things at the same time: change loadItems and create U2Ships. This is a direct violation of the single responsibility principle. Try to imagine the soldier who would try to shoot the gun and throw grenade at the same time! One thing at the time.
The problem is here:
while(tempShip.currentWeight<tempShip.weightLimit) {
if(tempShip.canCarry(tempItem)){
tempShip.carry(tempItem);
iterator.remove();
}
}
You are calling iterator.remove() within a loop. If the condition tempShip.canCarry(tempItem) holds twice, you call iterator.remove() twice, and this is not allowed (the second time, the item is already removed).
I don't know how the method canCarry is implemented, but note that if it is the case that tempShip.currentWeight<tempShip.weightLimit is true, but tempShip.canCarry(tempItem) is false, your loop will run forever.
use listIterator instead of Iterator.
ListIterator<Book> iter = books.listIterator();
while(iter.hasNext()){
if(iter.next().getIsbn().equals(isbn)){
iter.remove();
}
}
like used here.
Remove elements from collection while iterating
public ArrayList<Rocket> loadU2(ArrayList<Item> loadItems){
//list of ships
int shipNum=0;
int itemsloaded=0;
ArrayList<Rocket> U2Ships = new ArrayList<Rocket>();
while(!loadItems.isEmpty()) {
System.out.println("number of ships created: "+shipNum++);
//create a new ship
Rocket tempShip = new U2();
//loop over items check if it can be filled then only leave the load item that was not fully filled.
while(iterator.hasNext()) {
Item tempItem = iterator.next();
if(tempShip.canCarry(tempItem)){
System.out.println("number of items loaded: "+(itemsloaded++));
tempShip.carry(tempItem);
iterator.remove();
}
}
U2Ships.add(tempShip);
}
return U2Ships;
}
Thank you guys for the help, this should fix 2 problems: infinity, and the iterator.remove().
This function loops through a dictionary (allWords) and uses the
getKey function to generate a key. wordListMap is a HashMap> so I need to loop through and put the key and and a List. If there is not a list I put one if there is I just need to append the next dictionary word. This is where I need help. I just can't figure out the syntax to simply append the next word to the list that is already there. Any Help would be appreciated.
public static void constructWordListMap() {
wordListMap = new HashMap<>();
for (String w : allWords) {
int key = getKey(w);
if (isValidWord(w) && !wordListMap.containsKey(key)) {
List list = new ArrayList();
list.add(w);
wordListMap.put(key, list);
} else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
}
}
map.get(key).add(value)
Simple as that.
So I've gathered that you want to, given HashMap<Integer, List<String>>, you'd like to:
create a List object
add String objects to said List
add that List object as a value to be paired with a previously generated key (type Integer)
To do so, you'd want to first generate the key
Integer myKey = getKey(w);
Then, you'd enter a loop and add to a List object
List<String> myList = new List<String>;
for(int i = 0; i < intendedListLength; i++) {
String myEntry = //wherever you get your string from
myList.add(myEntry);
}
Lastly, you'd add the List to the HashMap
myHash.put(myKey, myList);
Leave any questions in the comments.
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.put(key, wordListMap.get(key).add(w));
}
If you want to add a new value to your list, you need to retrieve that list first. In the code above, you are putting the return value of add into the table (which is a boolean), and that is not what you want.
Instead, you will want to do as Paul said:
else if (isValidWord(w) && wordListMap.containsKey(key)) {
wordListMap.get(key).add(w);
}
The reason this works is because you already added an ArrayList to the table earlier. Here, you are getting that ArrayList, and adding a new value to it.
I have a List full of URLs, within that List there are many URLs I want to remove. The ones that I do want contain a specific string. Here is the code I have:
String website = "www.yahoo.com";
List<String> links = App.extractLinks(website); // this gets the links (URLs)
for(int i = 0; i < links.size(); i++) {
if(links.get(i).contains("XAB")) {
}
Now I know I can create a new List and do a .add(i) but that would just put in the indexes (because it is an integer) but I want to create a new List that has just the URLs I want. That is, I need a list and not a string because I need to access them one at a time in later code. There are about 80 different URLs
for (Iterator i = links.iterator(); i.hasNext();) {
if (!links.next().contains("XAB"))
i.remove();
}
If you want to remove items from your List during iteration, you can use an Iterator.
Iterator<String> iterator = links.iterator();
while(iterator.hasNext()) {
// you need to invoke Iterator.next before manipulating the List
// or any of its items
if (!iterator.next().contains("XAB")) {
iterator.remove();
}
}
If instead, you only want to create a new List with the "XAB" Strings, you can use fast-enumeration:
List<String> myXABList = new ArrayList<String>();
for (String s: links) {
if (s.contains("XAB")) {
myXABList.add(s);
}
}
I've some code below as that I use for querying the db and adding data to the list,
Query q= session.createQuery("select tally_receipt_prefix, tally_receipt_no, tally_head, tally_amount from Tally_table where tally_system_date='"+fmtd_date+"' and tally_dbcr_indicator='DB' and tally_mode='Ca' order by tally_head,tally_receipt_prefix,tally_receipt_no");
payincash = new ArrayList();
for(Iterator it=q.iterate(); it.hasNext(); )
{
Object[] row= (Object[]) it.next();
payincash.add((String)row[0]);
payincash.add((String)row[1]);
payincash.add((String)row[2]);
payincash.add((String)row[3]);
}
System.out.println("cash list in dao: "+payincash);
The list returned looks something like [prefix1, no1, head1, amt1, prefix2, no2, head2, amt2,]. I'm trying to make a receipt in jsp on the lines of
head1
prefix1/no1 amt1
prefix2/no2 amt 2
head3
prefix3/no3 amt3
So seemingly I want to group all records by head column in the receipt - jsp file. How do I go about this? Any help completely appreciated. Please excuse my English.
Edit: Here is what I tried,
Query q= session.createQuery("select tally_receipt_prefix, tally_receipt_no, tally_head, tally_amount from Tally_table where tally_system_date='"+fmtd_date+"' and tally_dbcr_indicator='DB' and tally_mode='Ca' order by tally_head,tally_receipt_prefix,tally_receipt_no");
System.out.println("query "+q);
List heads=new ArrayList();
for(Iterator it=q.iterate(); it.hasNext(); )
{
Object[] row= (Object[]) it.next();
payincash1=new LinkedHashMap<String, List>();
heads.add((String)row[2]);
List tails = null;
tails=new ArrayList();
tails.add((String)row[0]);
tails.add((String)row[1]);
tails.add((String)row[3]);
System.out.println("heads in dao from iter 1: "+heads);
System.out.println("tails in dao from iter1 on: "+tails);
if(heads.contains((String)row[2])) // for head in temp list
{
System.out.println("in first if");
if(payincash1.containsKey((String)row[2]))
{
System.out.println("map if repeat: "+payincash1);
payincash1.put((String)row[2],tails);
}
}
else
{
System.out.println("map if not repeat: "+payincash1);
payincash1.put((String)row[2], tails);
}
}
Where is the head column of the receipt stored? at what column?
In my humble opinion it should be stored at the database as well.
Let's say the head information is kept in column "head" at DB, so you should change your query, by adding:
order by head
At the end.
After that, you should iterate over the Result, and maybe keep the information in a data structure that looks like this:
Map<String,List<ReceiptInformation> map = new HashMap<>(); //using JDK7 syntax here
The key in the map should be the value of "head" in each iteration.
The value in the map should be an ArrayList (or any other class implementing List) that holds ReceiptInfo objects.
ReceiptInfoObject holds all the rest of the values per record.
Then, you can iterate on the map.keySet() collection , and for each key, prting the head, and then print the receipts using an internal loop.
Edited per request of the user who asked the question:
In order to add new entries (i.e - new RecepitInformation object to the map) one should perform:
List<RecepitInformation> listForHead = map.get(headValue);
if (listForHead == null) {
listForHead = new ArrayList<ReceiptInformation>();
map.put(headValue,listForHead);
}
listForHead.add(recepitInformation);
As usual, I did not compile this, but i think it should work
With GS Collections you can use list.groupBy(Function) as long as your list is a MutableList. For a JDK list, you could use Iterate.groupBy(Iterable, Function). The result of groupBy will be a Multimap.
I have an ArrayList that contains some object, such as User, and each object has a name and password property. How can I delete only the User object that has a specific 'name' from this ArrayList?
Iterator<User> it = list.iterator();
while (it.hasNext()) {
User user = it.next();
if (user.getName().equals("John Doe")) {
it.remove();
}
}
You could use something like this:
// If you are using java 8
userList.removeIf(user-> user.getName().equals("yourUserName"));
// With older version
User userToRemove = null;
for(User usr:userList) {
if(usr.getName().equals("yourUserName")) {
userToRemove = usr;
break;
}
}
userList.remove(userToRemove);
Another thought: If User class can be uniquely defined by the username and if you override equals with something like:
public boolean equals(Object arg0) {
return this.name.equals(((user) arg0).name);
}
You can remove the User without iterating through the list . You can just do :
list.remove(new User("John Doe"))
You are probably faced with the ConcurrentModificationException while trying to remove object from the List. An explanation for this exception is that the iterator of the ArrayList is a fail-fast iterator. For example, it will throw an exception (fail) when it detects that its collection in the runtime has been modified. The solution to this problem is to use the Iterator.
Here is a simple example that demonstrate how you could iterate through the List and remove the element when specific condition is met:
List<User> list = new ...
for (Iterator<User> it = list.iterator(); it.hasNext(); ) {
User user = it.next();
if (user.getUserEmail().equals(currentUser.getUserEmail())) {
it.remove();
}
}
Recommended way to solve this problem is:
ArrayList<User> list = new ArrayList<User>();
list.add(new User("user1","password1"));
list.add(new User("user2","password2"));
list.add(new User("user3","password3"));
list.add(new User("user4","password4"));
Iterator<String> iter = list.iterator();
while (iter.hasNext())
{
User user = iter.next();
if(user.name.equals("user1"))
{
//Use iterator to remove this User object.
iter.remove();
}
}
Using Iterator to remove an object is more efficient than removing by simply typing ArrayList(Object)
because it is more faster and 20% more time saving and a standard Java practice for Java Collections.
You could:
loop over the list with an iterator
check if each item in your list is the right user (checking the name)
if it is, use the remove method of the iterator.
Just search through the ArrayList of objects you get from the user, and test for a name equal to the name you want to remove. Then remove that object from the list.
Your code might look like this:
List<User> users = new ArrayList<User>();
public void removeUser(String name){
for(User user:users){
if(user.name.equals(name)){
users.remove(user);
}
}
}
ArrayList<User> userList=new ArrayList<>();
//load data
public void removeUser(String userName){
for (User user: userList){
if(user.getName()equals(userName)){
userList.remove(user);
}
}
}