How to remove unwanted items in a List - java

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);
}
}

Related

How do I find in Java a specific element, for printing, in a list of objects with multiple elements?

Long story short I parsed all the json from here
into a list of objects. But I'm having trouble trying to find a specific object. With all the examples on searching lists online I can't seem to be able to get it.
I ask the user to input a number into int checkId and checkUserId and then compare it. If it matches it should print out the title.
Iterator < Post > iter = posts.iterator();
while (iter.hasNext()) {
if (Objects.equals(iter.next().getUserId(), checkUserId)) {
System.out.println("found UserId");
if (Objects.equals(iter.next().getId(), checkId)) {
System.out.println("found Id");
//prints the title of object
}
}
}
And then I tried to use a stream
List<Post> result = posts.stream()
.filter(title -> checkId.equals(getId()))
.findAny()
.orElse(null);
All the code I cloned it from this great guy. https://github.com/danvega/httpclient-tutorial
Your first attempt does not work because you are advancing the iterator twice on each iteration by calling next. Instead, store the result of Iterator#next and use it.
Iterator<Post> iter = posts.iterator();
while(iter.hasNext()){
Post post = iter.next();
if(Objects.equals(post.getUserId(), checkUserId)) {
System.out.println("found UserId");
System.out.println(post.getTitle());
}
}
With streams:
List<String> titles = posts.stream().filter(post-> checkId.equals(post.getId()))
.map(Post::getTitle).collect(Collectors.toList());
titles.forEach(System.out::println);

How to compare elements inside List of strings with Array List of string?

I have added products to my basket and listed their URL in a List and want to verify these products against given String[] of products
the items are stored backwards in z String[] so the last item here is the 1st item in the List .. the number of items is 3 and below code works for 2 items and throw invoker exception at the assert method in the third item
public void verifyBag(String[] goods) {
actions.clickOn(By.xpath(bagLocator));
Arrays.sort(goods);
List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
List <String> actualItems = new ArrayList<String>();
for(int i=0;i<listItems.size();i++)
{
actualItems.add(listItems.get(i).getAttribute("href"));
}
int j = goods.length-1;
for(int i=0;i<goods.length;i++)
{
String actualItem = actualItems.get(i);
String product = goods[j];
System.out.println(product);
//assertTrue(actualItems.get(i).contains(goods[j]));
assertTrue(actualItem.equals(product));
j--;
}
assertEquals(listItems.size(), goods.length,"Assert Number of Items in the Bag");
}
If you don't care about the order, but about the match between provided list of goods and actualItems, you can do this:
Convert input array String[] goods into some collection, for example List. Lets call it goodsList.
From goodsList, remove all items that are also in actualItems.
If resulting set is empty, it means all items from goodsList are
also in actualItems.
If resulting set is not empty, it will contain list of items that are missing in actualItems comparing to goodsList
You can also do the reverse: from actualItems, remove all items that are also contained in goodsList. That gives you list of items that were not present in provided list.
Code:
public void verifyBag(String[] goods) {
actions.clickOn(By.xpath(bagLocator));
List<WebElement> listItems = actions.driver.findElements(By.xpath(bagItems));
List <String> actualItems = new ArrayList<String>();
for(int i=0;i<listItems.size();i++)
{
actualItems.add(listItems.get(i).getAttribute("href"));
}
List<String> goodsList = new ArrayList(Arrays.asList(goods));
goodsList.removeAll(actualItems);
if(goodsList.size() == 0) {
// All goods from provided goods list are also in actualItems
}
else {
// Some items didn't match
}
You have to check the size of goods and actualItems before doing the loop. Make sure that array and list have the same size and both of them is not null or empty.
Function listItems.get(i) and getAttribute("href") can return a null value, please check it before add to list.

Llist of items that have been deleted

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.

Get an element through an iterable string (guava)

I have an Iterable string (guava library). How can I get elements from it. Here is my code:
public static String hillcipher(String str)
{
String hillcipher="";
Iterable<String> pieces = null;
for (int i=0; i<=str.length()-1; i++){
char c = str.charAt(i);
if (Character.isLetter(c)){
pieces = Splitter.fixedLength(2).split(str);
}
}
System.out.println(pieces);
return hillcipher;
here i split a string into pieces of 2 chars each. for example "java" wil be splided to "ja", "va". But then i want to get each character separatly just to do other calculations on them.
There are various ways to get an element from an iterable:
Iterate over each element:
for (String piece : pieces) {
// do something
}
or
Iterator<String> iterator = pieces.iterator();
while (iterator.hasNext()) {
String piece = iterator.next();
// do something
}
etc.
iterating through just the first N elements you want if present:
Iterator<String> iterator = pieces.iterator();
if (iterator.hasNext()) {
String firstPiece = iterator.next();
// do something
if (iterator.hasNext()) {
String secondPiece = iterator.next();
// do something else
// etc.
}
}
using helper functions like those in Guava's Iterables:
String thirdPiece = Iterables.get(pieces, 2);
or
String lastPieceOrEmpty = Iterables.getLast(pieces, "");
etc.
However, if you'd like to simply access the elements like you would a list you can use Splitter.splitToList(CharSequence) instead. It is the same as Splitter.split(CharSequence) but instead of returning a potentially lazy evaluated Iterable it returns a populated ImmutableList which supports random access to its elements.

How can I add a string one at a time to a HashMap<Integer, List<String>>?

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.

Categories

Resources