Selenium WebDriver Java Cycle of adding words in the same field - java

This is my first message and it can looks like newbie, but I need your help)
My objective is to add pairs of words from some list, click on Add button, then repeat action with another pair of words. So I created method, which receives 2 words, add them to fields and presses add button.
public static void addWord(String eng, String rus) {
driver.findElement(By.xpath("//input[contains(#placeholder, 'English Word')]")).sendKeys(eng);
driver.findElement(By.xpath("//input[contains(#placeholder, 'Russian Word')]")).sendKeys(rus);
driver.findElement(By.xpath("//button[contains(#class, 'add')]")).submit();
}
So if I do it manually by using addWord("Hello", "Привет"); it works, but I have a big list of words and want to write code, which will get pair of words from list and add them to method, then repeat until all words will be added. Please advice me how it can be done, maybe using arrays and cycles, but I don't know how to do it correctly.

You can create a Map with the key pairs and then iterate trough it:
Map<String, String> yourMap = new HashMap<String, String>()
{
{
put("Hello", "Привет");
put("Hello 2", "Привет 2");
// Add all the inputs needed
}
};
public static void addWord(Map yourMap) {
yourMap.forEach((eng, rus) -> {
driver.findElement(By.xpath("//input[contains(#placeholder, 'English Word')]")).sendKeys(eng);
driver.findElement(By.xpath("//input[contains(#placeholder, 'Russian Word')]")).sendKeys(rus);
driver.findElement(By.xpath("//button[contains(#class, 'add')]")).submit();
});
}

Related

Java - How do I add a new value to an existing key in a Hash Map. 1 key, multiple values

I am trying to create a method that, when given a key and a value, can access the map via the key and then either add or replace that specific value.
My Hash Map is created like so:
public Band(){
musicians = new HashMap<>();
}
And I can add new entries like so, with band acting as the key:
public void addMapEntry(String band, String name, String instrument, int experience){
musicians.put(band, new Musician(name, instrument, experience));
}
My new method header look like this:
public void addValue(){ }
I have tried using the put method but I can't get it work as I'd like.
I have also tried iterating through the map, but I've only ever used that method to return map objects in a list, whereas I don't want to return anything in this method. I want to be able to send it two arguments (the key and the value) and have it only replace that specific value.
I hope I have been clear in my explanation.
Java Map is single value for each key.
If you need multiple values for a single key, you should make the type a collection of the appropriate type and add your own logic for adding a new value. Your Band class should have methods to add/remove a Musician and handle the details in the private implementation.
public class Band {
private Map<String, List<Musician>> members = new HashMap<String, List<Musician>>();
public void addMusician(String key, Musician musician) {
if (this.members.containsKey(key) {
List<Musician> musicians = this.members.get(key);
if (musician != null) {
musicians.add(musician);
this.members.put(key, musicians);
}
}
}
public void removeMusician(String key, Musician musician) {
// should be clear enough from the add method.
}
}
I think the most suitable for you is to use Guava Multimap
ListMultimap<String, String> musicianMap = ArrayListMultimap.create();
Then add as many musicians to your band
musicianMap.put("Beatles", new Musician("Jhon Lennon"));
musicianMap.put("Beatles", new Musician("Paul McCartney"));
musicianMap.put("Beatles", new Musician("Ringo Starr"));
musicianMap.put("Beatles", new Musician("George Harrison"));
And you can pull them all using just key.
musicianMap.get("Beatles")
This will return a list of ["John Lenon", "Paul McCartney", "Ringo Starr"] of course these will objects of class Musician.

Java - continuously check if the new value in an arraylist is unique

I have an arraylist full of usernames that I am hoping to display on a webpage. At the moment my arraylist looks like this:
[user=johndoe, user=sampletest, user=johndoe, user=myusername, user=myusername, user=terryh, user=terryh, user=johndoe]
How do I get my arraylist to look like this:
[user=johndoe, user=sampletest, user=myusername, user=terryh]
I've tried other answers but none of them seem to work for me
You may want to simply stop using ArrayList and rather, use a Set. Since all of the element are users, you can discard user= before each element, but I'll keep it in the following code for continuity.
Set<String> userSet = new LinkedHashSet();
For example, in the code below:
public static void main(String[] args) {
Set<String> userSet = new LinkedHashSet<String>();
userSet.add("user=johndoe");
userSet.add("user=sampletest");
userSet.add("user=johndoe");
userSet.add("user=myusername");
userSet.add("user=myusername");
userSet.add("user=terryh");
userSet.add("user=terryh");
userSet.add("user=johndoe");
for (String user : userSet) {
System.out.println(user);
}
}
The output is just:
user=johndoe
user=sampletest
user=myusername
user=terryh

How to remove the selected item from Arraylist<HashMap<String, String>> in android

I am using Arraylist < HashMap< String, String >> in ListView to archive multi-column(I just need two column, so I use HashMap). But when I am using remove method in context menu. It would always remove the last item in the list.
The code:
#Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.bc_contextmenu_delete:
list.remove(info.position);
adapter.notifyDataSetChanged();
return true;
default:
return super.onContextItemSelected(item);
}
}
What should I do to solve this problem to remove the selected one from the list?
Besides, I would also like to get those two values from the HashMap which in the ArrayList. Which code should I use here.
Here is an ArrayList:
PS4 4000<br>
PS5 5000<br>
XBOX 6000<br>
I would like to get PS4 and 4000.
Thanks all.
As per your requirement, you can create a bean for same. i.e. DummyBean. it has two field like
class DummyBean{
String name;
String val;
--getter setter method
}
Use it into List<DummyBean>.
In future if new column added than it is easy to add and expandable.
No need to wrap the HashMap into an ArrayList. HashMap itself is enough. If you want to remain the order, you should use LinkedHashMap.
A side effect is that you cannot access elements by index, so you have to iterate over it to get the last item or the one by index.
So if you don't care about duplicates I would use ArrayList with as template a Pair or a custom Object. (Where I prefer a custom object to be more readable)
ArrayList<Pair<String,String>> consoles = new ArrayList<Pair<String,int>>();
consoles.Add(Pair.create("PS4", 4000));
consoles.Add(Pair.create("PS5 ", 5000));
consoles.Add(Pair.create("XBOX ", 6000));
And remove using index:
consoles.Remove(index);
To store and retrieve your values from the Hashmap in ArrayList, You need to store the the HashMap values with keys to identify them
As with your example ,
PS4 4000
PS5 5000
XBOX 6000
ArrayList<HashMap<String ,String>> list = new ArrayList<>();
// to add item
HashMap<String ,String> val = new HashMap<>();
val.put("GAME", "PS4");
val.put("NUMBER", "4000");
list.add(val); //added to 0th index position
val = new HashMap<>();
val.put("GAME", "PS5");
val.put("NUMBER", "5000");
list.add(val); //added to 1st
// to retrieve ps4 and 400
String forPS4 = list.get(0).get("GAME");
String for4000 = list.get(0).get("4000");

Check value inside Map

I have a Map where I save values with the form NAME-GROUP.
Before doing some operations, I need to know if the Map contains a specific group,
for example: I need to check for values containing group1 like Mark-group1.
I'm trying to get it this way:
if (checkList.containsValue(group1)) {
exists = true;
}
I can't provide the name when searching because there could be diferent names with the same group.
But it isn't finding the value, as seems that this function just looks for the entire value string and not only for part of it.
So, there would be any way of achieving this, or would I need to change the way I'm focusing my code.
Update--
This is the looking of my Map:
Map<Integer, String> checkList = new HashMap<Integer, String>();
I load some values from a database and I set them into the Map:
if (c.moveToFirst()) {
int checkKey = 0;
do {
checkKey++;
checkList.put(checkKey, c.getString(c.getColumnIndex(TravelOrder.RELATION)));
}while(c.moveToNext());
}
The relation column, has values like: mark-group1, jerry-group1, lewis-group2, etc...
So, the Map will have a structure like [1, mark-group1], etc...
What I need is to check if there is any value inside the map that contains the string group1 for example, I don't care about the name, I just need to know if that group exists there.
If you want to check any value contain your string as a substring you have to do the following:
for (String value : yourMap.values()) {
if (value.contains(subString)) {
return true;
}
}
return false;
By the way if your values in the map are really have two different parts, i suggest to store them in a structure with two fields, so they can be easily searched.

Create dynamic ArrayLists

I have a problem related to "dynamic ArrayLists". I have a List that contains usernames and their data. I want for every distinct username to create a single list that contains all data of this user. For example, I have an arraylist (username,tweet) that has: lefteris,"Plays ball", Kostas, "Plays basketball", lefteris, "Nice weather". And I want after that to create two lists. One list with kostas and his tweets and another with lefteris and its tweets (2 tweets). The parent arraylist may have 20 distinct usernames or more. How can I do that ?
I recommend you to use hashmap or hashset instead because if you need to store something in pairs, hashing is a perfect solution......
I'd go with the following data structure:
HashMap<String, ArrayList<String>>
Then you could manipulate a "dynamic" list of properties keyed to each name, if the properties are single items:
Lefteris->("Plays ball", "Nice weather",...)
Kostas->("Plays basketball",...)
If the properties are key-value pairs, do:
HashMap<String, HashMap<String, Object>>
Data looking like:
Lefteris->(Sport->"Plays ball", Weather->"Nice",...)
Kostas->(Sport->"basketball",...)
Since you parse the items from a file, you can do the following.
Create a map that contains the tweets associated to a particular username
Map<String,List<String>> userTweets = new HashMap<String,List<String>>();
Then, have a method to associate a tweet to certain user, verifying that it is already added in the map and adding it if it isn't.
public void addTweetToUser(String user, String tweet) {
if(userTweets.containsKey(user))
userTweets.get(user).add(tweet);
else {
List<String> newUserTweets = new LinkedList<String>();
newUserTweets.add(tweet);
userTweets.put(user, newUserTweets);
}
}
As a plus, you can improve this by creating an object UserTweet that contains:
public class UserTweet {
private String user;
private String tweet;
//Constructor, Setters & Getters or all of them
}
Then your addTweetToUser method can have an UserTweet parameter instead.
When you want to know the tweets for a certain user, you just obtain the corresponding list from the userTweets map. I alsomethods to remove tweets and/or remove users, just in case.
Several libraries add excellent collection-processing functionality to Java along the lines of what functional languages provide. One such library is Google Guava. Guava provides a MultiMap suitable for grouping things the way you want. There are also many utility methods, like MultiMaps.index(), which collects items from a list into a map by applying some function to the elements of the list to calculate a key. With such support, it only takes a few lines of code and one Function implementation (a closure in any other language) to solve your problem:
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.util.Arrays;
import java.util.List;
public class Tweets {
public static final int NAME = 0;
public static final int TWEET = 1;
public static void main(String[] args) {
List<String> namesAndTweets = Arrays.asList(
"lefteris", "Plays ball",
"Kostas", "Plays basketball",
"lefteris", "Nice weather");
List<List<String>> nameTweetPairs =
Lists.partition(namesAndTweets, 2);
Multimap<String, List<String>> namesAndTweetsByName =
Multimaps.index(nameTweetPairs, get(NAME));
Multimap<String, String> tweetsByName =
Multimaps.transformValues(namesAndTweetsByName, get(TWEET));
System.out.println(tweetsByName);
}
private static Function<List<String>, String> get(final int n) {
return new Function<List<String>, String>() {
#Override
public String apply(List<String> nameAndTweet) {
return nameAndTweet.get(n);
}
};
}
}
Outputs:
{lefteris=[Plays ball, Nice weather], Kostas=[Plays basketball]}
Update: To explain the code a bit more, there are three basic steps:
Take the list that has names and tweets all mixed together and use Lists.partition() to break it into pairs of (name, tweet).
Use MultiMaps.index() to build a MultiMap from the pairs, taking the name as the map key. This gives you a map where map keys are names and map values are the (name, tweet) pairs.
Use MultiMaps.transformValues() to reduce the map values from (name, tweet) pairs to just the tweets.
P.S. does anyone know if there's a built-in Function that does what my get() does? It seems like a useful Function that should be provided, but I can't find it anywhere.

Categories

Resources