I have 10 array lists and a String variable.
I have one function/method that allows the user to select one of the array lists to add to. Currently, that function changes the value of a string "chosen" to the value of the proper array list name.
Another function is started in which adding elements to the arraylist happens. However, I am struggling to come up with a solution on how to change which arraylist is being added to based upon what was selected by the user.
This code doesn't work but say it was:
chosen.add(whatUserEntered);
Normally you can put in the arrayList name and add .add(whateverTheUserIsEntering) and itll work fine.
So how can I have the name of an arrayList equal that of a String variable's value?
Here is an example using a Map to bind string names to lists. When you need to put things together at run time (as opposed to compile time, as you show with your example choosen.add(userEntered)), you usually need to use a Map.
This works with strings read from a file (say to bind XML names to objects) or things like interpreters where you have to keep track of user variables by name.
public class SymbolTableExample
{
public static void main(String[] args) {
// Some array lists
ArrayList<String> cats = new ArrayList<>();
ArrayList<String> dogs = new ArrayList<>();
ArrayList<String> beetles = new ArrayList<>();
ArrayList<String> cows = new ArrayList<>();
// Bind names to them
Map<String,List<String>> binding = new HashMap<>();
binding.put( "cats", cats );
binding.put( "dogs", dogs );
binding.put( "beetles", beetles );
binding.put( "cows", cows );
// Pretend the user enters some input here
String userChoice = "cats";
String userEntered = "flufy";
binding.get( userChoice ).add( userEntered );
}
}
Use a Map.
public interface Map<K,V>
You can use the method
V put(K key, V value)
to assign a value to a key, so you can set ArrayLists for different keys or add new ones..
Since you are using ArrayLists, you could make your make your Map like so:
Map<String, ArrayList<String>)> myArrays
Then, to add a value to an array with a given key, use
myArrays.get(userChosenArrayKey).add(whatUserEntered)
Related
I would like to get an entry from ArrayList in an ArrayListMultiMap. I am using Google Guava ArrayListMultimap and each key is associated with multiple array lists. For example, for the key1 I have 4 array lists, and each ArrayList contains 2 entries. I need to be able to access a particular ArrayList and get an entry from there so my question is how do I do it? Every time I try to access the value associated with the key it prints all 4 array lists but I need only one.
Multimap<String, ArrayList<String>> wordAsKey = ArrayListMultimap.create();
for (DictionaryEntries dict : DictionaryEntries.values()) {
ArrayList<String> list = new ArrayList<>();
String key = dict.getKey();
String partOfSpeech = dict.getPartOfSpeech();
String definition = dict.getDefinition();
list.add(partOfSpeech);
list.add(definition);
wordAsKey.put(key, list);
}
ArrayList<String> resultList = new ArrayList<>();
resultList.add(wordAsKey.get(word).toString());
System.out.println(resultList);
Prints
[[[noun, A set of pages.], [noun, A written work published in printed or electronic form.], [verb, To arrange for someone to have a seat on a plane.], [verb, To arrange something on a particular date.]]]
But I need it to print only [noun, A set of pages.]
you can try: get index value
int index = 0;
resultList.add(wordAsKey.get(word).get(index).toString());
Just do it like this -
ArrayList<String> list = (ArrayList<String>)wordAsKey.get(word);
String result = list.get(index);
System.out.println(result);
And you can check whether particular String is exist or not in List, then see below;
if(list.contains("search")){...}
Basically I will be given two large input files. One will be a list of words, the other will be that list of those same words, but the words will be scrambled. I have to use a HashMap to get the list of words and scrambled words and then print the scrambled word with the real word next to it in alphabetical order.
For example:
rdib bird
tca cat
gdo dog
etc.
I'm having some trouble so far. I have created a method to sort and get the key from the words, but I'm not sure where to go from there. I think I still need to work with the scrambled words and then print everything out. Any help explaining these things would be much appreciated, for this is my first time using a HashMap. My current, very incomplete code is below.
import java.io.*;
import java.util.*;
public class Project5
{
public static void main (String[] args) throws Exception
{
BufferedReader dictionaryList = new BufferedReader( new FileReader( args[0] ) );
BufferedReader scrambleList = new BufferedReader( new FileReader( args[1] ) );
HashMap<String, String> dWordMap = new HashMap<String, String>();
while (dictionaryList.ready())
{
String word = dictionaryList.readLine();
dWordMap.put(createKey(word), word);
}
dictionaryList.close();
while (scrambleList.ready())
{
String scrambledWords = scrambleList.readLine();
List<String> dictionaryWords = dWordMap.get(createKey(scrambledWords));
System.out.println(scrambledWords + " " + dictionaryWords);
}
scrambleList.close();
}
private static String createKey(String word)
{
char[] characterWord = word.toCharArray();
Arrays.sort(characterWord);
return new String(characterWord);
}
Make the dWordMap just HashMap<String, String>. For the line you're not sure of, do dWordMap.put(createKey(word), word).
Then loop through the scrableList and the word is dWordMap.get(createKey(scrambledWord)).
You should probably also handle the case that the scrambled word is not in the original word list.
The key concept to understand about a HashMap is that it makes it O(1) to test if the map contains a given key, and O(1) to retrieve the value associated with a given key. This means these operations take constant time--whether the map has 5 elements or 5000, it will take the same time to determine if the map contains "ehllo". If you want to check these two lists (dictionary and scrambled), you need a key that will be the same for both. As you have started to do in your solution, sorting the letters in the word is a good choice. So your HashMap will look something like this:
{
"ehllo": "hello",
"dlorw": "world"
}
One pass through the dictionary list builds that map, then another pass through it takes the scrambled word, sorts the letters in it, then checks the map to find the unscrambled word.
You should break this task down into smaller parts. Check each one works before moving on to the next.
First you need a method that turns a word into a key. A string containing the letters of the word alphabetised is a good key. So write something that passes the test:
assertEquals("dgo", createKey("dog");
assertEquals("act", createKey("cat");
Next you need to populate your map with words from your list. You need something that passes this test:
Map<String,String> map = new HashMap<>();
addToMap(map,"dog");
assertEquals("dog", map.get("dgo");
Your addToMap() method will make use of createKey().
It should now be clear that you can use the map you've created, and createKey() to find "dog" from any ordering:
Map<String,String> map = new HashMap<>();
addToMap(map,"dog");
assertEquals("dog", map.get(createKey("odg"));
You can encapsulate this into a method, so that:
Map<String,String> map = new HashMap<>();
addToMap(map,"dog");
assertEquals("dog", getFromScrambledWord(map,"odg"));
All that's left is to put it all together:
Loop through your dictionary file and call addToMap() for each line
Loop through your scrambled-word file, call getFromScrambledWord() for each one, print the result
If you also need to put this list in alphabetical order, then instead of printing it, store the result in a List, sort the list then loop through it to print.
I've deliberately made this not very object-oriented, because you're clearly a beginner. To make things more OO, make the Map a private field in a class of your own:
public class WordStore {
private final Map<String,String> words = new HashMap<>();
public void addWord(String word) {
// your implementation here
}
public String getFromScrambled(String scrambledWord) {
// your implementation here
}
}
So the test would be more like:
WordStore store = new WordStore(); // the Map is inside the WordStore
store.addWord("dog"); // like addToMap()
assertEquals("dog", store.getFromScrambled("odg"));
I don't have idea how to search this:
Random generator = new Random();
Map<Integer, ArrayList> mapOfprevOp = new HashMap<>();
ArrayList<Integer> listPrev = new ArrayList<>();
listPrev = mapOfprevOp.get(operacja);
System.out.println(listPrev); // it will show []
int rnd = generator.nextInt(op_cnt) + 1;
listPrev.add(rnd);
System.out.println(mapOfprevOp.get(operacja)); // it will show value of listPrev
Why second System.out print me on the screen value of listPrev?
It shouldn't still print [] ?
listPrev = mapOfprevOp.get(operacja);
This line works different than i could expect?
This would suggest that at your first System.out.println invocation the list is empty.
If you look here https://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html#toString%28%29. We can see that the toString method for a list returns the elements between square brackets. Thus [] is an empty list.
At the second call you have added an element which is why you see it. You need to bare in mind that in Java we pass objects by reference meaning that your listPrev references the SAME LIST as the one contained in the map.
If you want to just get the value, then I would suggest you change
listPrev = mapOfprevOp.get(operacja);
to be
listPrev.addAll(mapOfprevOp.get(operacja));
This will add all of the elements from mapOfprevOp.get(operacja) to listPrev without subsequent operations affecting the map which seems to be what you want.
Also, Map<Integer, ArrayList> mapOfprevOp = new HashMap<>(); Generally it is better to use interface types in delcarations like you have with Map. So I would consider switching ArrayList to be List.
The object that you use its self can still be an ArrayList, like this:
Map mapOfprevOp = new HashMap<>();
List listPrev = new ArrayList<>();
This means that if you wanted to change it to be a LinkedList, you would only change it in one place rather than 3. Note that with the exception of Arrays.asList lists all lists can be resized.
I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods
I have a Arraylist: ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
from an Object that includes a String and an double (Name and points).
public class PlayerBean{private String name;private double points;}
However for one of my Spinners I want to show only the name (String) in my Arraylist.
How do I manage to delete(remove) the double(points)?
I tried this without any success any ideas?
I am using the swinger for android. any idea?
ArrayList<PlayerBean> playerlist = new ArrayList<PlayerBean>();
List<String> namesOnly = filterNames(playerlist);
private List<String> filterNames(ArrayList<PlayerBean> playerlist12) {
List<String> names = new ArrayList<String>();
for(PlayerBean b : playerlist12)
{
names.add(b.getName());
}
return names;
}
Your list contains PlayerBean objects and you can't temporarily delete member variables from objects. Thus you can't remove points from the list.
You could either use a List<String> instead or provide a spinner model that only displays the name. I assume you're using Swing, don't you?
Rather than removing them, why don't you make a new array List of String type, and assign all the names into this list. So you don't have any points.