Suppose I have an array which contains the values
String studentList[] = {Paul, null, null};
Now I wanna add another student but make sure before if the student is not already in there.
I have already a for loop which checks if the value is null and if it is then add the student.
You should use a Set, HashSet as the exact implementation and convert that to array afterwards.
Add result to a hash set
1.HashSet contains unique elements only.
HashSet<String> studentList=new HashSet<String>();
studentList.add("Paul");
You'd be better off using a Set, however, you can do this:
String studentList[] = {"Paul", null, null};
for (int i = 0; i < studentList.length; ++i) {
if (studentList[i] == null) {
studentList[i] = newStudent;
break;
} else if (studentList[i].equals(newStudent)) {
break;
}
}
Related
Within Android, I'd like to perform an if statement to check whether an ArrayList contains any element from an array of Strings?
e.g.
Check whether any of the elements from singingGroup are also containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
How can I do this? as I know how to check if one item is contained as in another array as below. But not if any from one, exist in another.
if (Arrays.asList(Winners).contains(singingGroup)) {
You can use
Collections.disjoint(singingGroup, Arrays.asList(Winners));
to test, is the 2 arguments have no common element(s) in common. (see also javadoc)
The negation of the result seems to be what you're looking for.
Collections.disjoint is one way to archive this but You can also use retainAll() method.
Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.
Case I :elements from singingGroup are not containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
List<String> WinnerList = new ArrayList<>(Arrays.asList(Winners));
WinnerList.retainAll(singingGroup);
System.out.println("retainList = " + WinnerList);
Output
list1 = []
Case II:elements from singingGroup are also containined in Winners[]
String Winners[] = {"Jennifer", "Steven", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Steven");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Jennifer");
List<String> WinnerList = new ArrayList<>(Arrays.asList(Winners));
WinnerList.retainAll(singingGroup);
System.out.println("retainList = " + WinnerList);
Output
retainList = [Jennifer, Steven]
you can also check like this:
String Winners[] = {"Jennifer", "Patrick", "Peter", "Parker"};
ArrayList<String> singingGroup = new ArrayList<String>();
singingGroup.add("Patrick");
singingGroup.add("Jane");
singingGroup.add("Joe");
singingGroup.add("Susan");
singingGroup.add("Amy");
for(int i=0; i< Winners.length;i++)
{
if(singingGroup.contains(Winners[i]))
{
System.out.println("duplicate");
}
}
You can use the CollectionUtils class provided by Apache Commons.
Using the intersection method (useful if you want to do something with the common elements):
Collection<String> intersection = CollectionUtils.intersection(singingGroup, Arrays.asList(Winners));
if (intersection.size() > 0){
// At least one element contained in the intersection
}
Or, using the containsAny method:
if (CollectionUtils.containsAny(singingGroup, Arrays.asList(Winners))){
// True if at least one common element exists in both lists
}
//for loop would be perfect to check if element i = element i
int i =0;
int loopCount = 0;
while(loopCount < Winners.lenght)
{
for(int i =0; i < singingGroup.length; i++)
{
if(Winners[loopCount] == singingGroup[i])
{
System.out.println(Winners[loopCount] + "is apart of the winners");
}//end of comparing if
if(i == singing.Group.length)
{
loopCount ++;
} //end of i == singingGroup
}//end of for loop
}//end of while loop
This is not the most optimal code but if you need it in a hurry this will work
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 an array of contacts like so :
public class Application {
private Scanner input;
private Contact[] contacts;
private int ArrayNum;
public Application() {
input = new Scanner(System.in);
contacts = new Contact[5];
ArrayNum = 0;
}
And what I want to do is enter a name of someone on the contacts list and if they are found on their list return their index like so:
System.out.println("Who do you want to remove?");
String name = input.nextLine();
for(Contact c: contacts){
if(c.getName().equals(name)){
//Get the index here
}
}
I tried researching this but no answer or guide seems to be very clear on this so I'm hoping that someone can explain this for me.
Thank you for looking
for(int index = 0; index < contacts.length; index++) {
if(contacts[index].getName().equals(name)) {
// use the index here
}
}
I don't think this code snippet needs any further explanation.
Use a for loop that uses a counter instead.
for(int i = 0; i < contacts.length, i++) {
if(contacts[i].getName().equals(name)) {
// do something with the index, i
}
}
You could use a counter
System.out.println("Who do you want to remove?");
String name = input.nextLine();
int remove_index = -1;
for(int i=0; i<contacts.length; i++){
Contact c = contacts[i];
if(c.getName().equals(name)){
remove_index =i;
}
}
Another alternative that may be helpful down the line is to use an ArrayList<Contact> instead of a c-style array (Contact[]). This class might add more handling complexity than it's worth, but it includes a lot of useful extra methods, including an int indexOf(<T> object) where <T> is the type you specified in your declaration (i.e., Contact for ArrayList<Contact> contacts).
Bad idea! You can't do that seriously, if you have an array. Of course you can set an index to null, but then you have to search for a null entry to reference a new contact within the array.
Note: you have an Iterator while writing
for(Contact c: contacts){...
So one option is to iterate by index, but it's a bad option. Better make your Array a Set. Then you might write:
for (Iterator<Contact> iter = mySet.iterator();iter.hasNext();) {
final Contact next = iter.next();
if(next.getName() == "NAME") {
iter.remove();
break;
}
Always use Iterator.remove()! Otherwise you will get Exceptions earlier than you wish :D
Hi community I have a question, I happen to have an array of objects loaded on startup, through that generate array another array of integers that contains your code, it appears that array of integers'm removing their values, what I want is to compare the list of integer array currently have with the array of objects, and remove all code object that whole array mentioned is found.
My code java:
private List<ValidColumnKey> columnCustomer;
private int[] selectedCustomer;
public void init(){
this.setColumnCustomer(new ArrayList<ValidColumnKey>());
this.getColumnCustomer().add(new ValidColumnKey(1, "Codigo", "code"));
this.getColumnCustomer().add(new ValidColumnKey(2, "Nombre", "name"));
this.getColumnCustomer().add(new ValidColumnKey(3, "Nombre Comercial", "comercialName"));
this.getColumnCustomer().add(new ValidColumnKey(4, "Estado", "isActive"));
this.setSelectedCustomer(new int [this.getColumnCustomer().size()]);
int i = 0;
for(ValidColumnKey column : this.getColumnCustomer()){
this.getSelectedCustomer()[i] = column.getCodigo();
i++;
}
}
I mean I would have my array of integers with codes removed, like this:
selectedCustomer = [1, 2, 3];
What I wanted was to remove from the list of objects that do not have codes in the array of integers, but it is not my code:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
for(ValidColumnKey column : this.getColumnCustomer()){
for(Integer codigo : this.getSelectedCustomer()){
if (column.getCodigo() != codigo) {
auxRemoColumnKeys.add(column);
break;
}
}
}
this.getColumnCustomer().remove(auxRemoColumnKeys);
I could guide the solution.
this.getColumnCustomer().remove(auxRemoColumnKeys);
This statement assumes you have a valid equals method for your class ValidColumnKey, which I suspect is probably not the case.
What you want to do is iterate with a Iterator. Some sample code could be like
Set<Integer> toRemoveCodes = new HashSet<Integer>(Arrays.asList(1, 2, 3));
for (Iterator<ValidColumnKey> it = this.getColumnCustomer().iterator(); it.hasNext(); ) {
ValidColumnKey curColumnKey = it.next();
Integer code = curColumnKey.codigo();
if (toRemoveCodes.contains(code)) {
it.remove();
}
}
There are multiple reasons your current attempt is failing. The first is that this line:
if (column.getCodigo() != codigo) {
Is testing for object equivalence between Integers, not value equavalence between ints. If you want to compare Integers, you have to use the equals method:
if (!column.getCodigo().equals(codigo)) {
However, if getCodigo returns an int and getSelectedCustomer returns an int[] then this line should be changed instead:
for(int codigo : this.getSelectedCustomer()){
Because you didn't need to use Integer in the first place.
Secondly, this line attempts to remove auxRemoColumnKeys itself so you probably mean removeAll:
this.getColumnCustomer().remove(auxRemoColumnKeys);
Lastly, your logic is generally flawed. It basically says "for each element in getColumnCustomer, if getCodigo is not equal to all of getSelectedCustomer remove it". I don't think that's what you've intended.
This is a modified loop that uses the same "add to a list and remove the list items" procedure but the logic will work:
List<ValidColumnKey> auxRemoColumnKeys = new ArrayList<ValidColumnKey>();
int[] selected = this.getSelectedCustomer();
for (ValidColumnKey column : this.getColumnCustomer()) {
int i = 0;
for ( ; i < selected.length; i++) {
/* note: if getCodigo returns an Integer change this check to
* "if (column.getCodigo().equals(selected[i])) {"
*/
if (column.getCodigo() == selected[i]) {
break;
}
}
/* this says "if the search loop did not break early" */
if (i == selected.length) {
auxRemoColumnKeys.add(column);
}
}
this.getColumnCustomer().removeAll(auxRemoColumnKeys);
I have to add a String parameter to the end of an array. And throw an exception if the String already exists in the array. I don't know. Can anyone help?
This is what I have so far
public static void addCity (String city) throws Exception
{
for (int i = 0; i < MAX_CITIES;i++)
{
if (city == cityNames[i])
throw new Exception("This city already exists");
}
String [] temp = new String[cityNames.length+1];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
temp[temp.length-1] = city;
cityNames = temp;
manyItems++;
}
To test if String a equals String b, use a.equals(b), not a == b.
(a == b works in C++, not Java.)
Your code looks fine except for the String comparison:
if (city == cityNames[i])
This won't do a proper String comparison: it will only compare the object references, which will usually be false.
Use String.equals for this:
if (city.equals(cityNames[i]))
It'd be easier to use a List:
List<String> cityNames = new ArrayList<String>();
if(cityNames.contains(city)) {
throw new Exception("This city already exists");
}
cityNames.add(city);
What is MAX_CITIES? I think your first loop should be until i < cityNames.length, not MAX_CITIES, since you don't seem to be updating MAX_CITIES when you increase the size of the array.
You should be using the equals() method to compare String objects, rather than ==.
It also might be nice if instead of just making the new array one element bigger, you double the size. That way you don't have to go through all the work of copying the array every time you add a new element. You'd need a variable to keep track of the next empty spot in the array, and it would look something like this:
if (nextEmptyIndex == cityNames.length)
{
String [] temp = new String[cityNames.length*2];
for (int i = 0; i < cityNames.length;i++) {
temp[i] = cityNames[i];
}
}
temp[nextEmptyIndex] = city;
nextEmptyIndex++;
manyItems++;