I tried Arrays.asList().contains(string) to compare array items with string but return is false every time even emailid matches .
This is my array:
List<String> arraySE = new ArrayList<String>();
if(Arrays.asList(arraySE).contains(c.getString(c.getColumnIndex(KEY_EMAIL)))){
user.setSelected(true);
} else{
user.setSelected(isSelect);
}
Sample ARRAY:
[user1#gmail.com, user2#gmail.com, user3#gmail.com]
NO ERROR, returning false
A primitive example that works correctly:
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("Hello");
arrayList.add("Hola");
arrayList.add("Hallo");
boolean contains = arrayList.contains("Hello");
System.out.println(contains);
}
}
I would recommend that you debug through your code and especially see what c.getString(c.getColumnIndex(KEY_EMAIL)) returns.
boolean isThere = Arrays.asList(yourArray).contains("test");
if(isThere){
}
else{
}
At first, your list in your example is empty.
Sencodly, you don't need to use Arrays.asList(arraySE), because it is already a list.
You can simply use the contains function to check:
List<String> arraySE = Arrays.asList("user1#gmail.com", "user2#gmail.com", "user3#gmail.com");
if (arraySE.contains("user1#gmail.com")) {
System.out.println("true");
} else {
System.out.println("false");
}
You already have a list of strings, call contains on it. It will work if a match is found.
Why it is failing now is basically when you are calling asList the returned list is not a list of strings, so equals method works differently in that case.
import java.util.ArrayList;
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
String str[] = {"A","B","C","D"};
ArrayList a = new ArrayList(Arrays.asList(str));
System.out.println(a.contains("A"));
}
}
Related
So I have recently started my work on Selenium Webdriver using Java. Below is the code:
List<LineDashboardDetails> LineDashboardDetailList = new ArrayList<LineDashboardDetails>();
LineDashboardDetails objLineDetail = new LineDashboardDetails();
for (int i = 0; i < lineUITextList.size(); i++) {
objLineDetail.lineName=lineUITextList.get(i);
objLineDetail.machineNames = machineUITextList.get(i).toString();
LineDashboardDetailList.add(objLineDetail);
}
System.out.println(LineDashboardDetailList);
I have created a lineUITextList ArrayList of String. This array will always have only 1 value in it. So the issue is above for loop does not work. The loop only executes once and comes out to print the LineDashboardDetailList. The machineUITextList array has around 5-6 values in it. My expectation is to have LineDashboardDetailList such that the lineUITextList common value is paired with each new value of machineUITextList.
For example if lineUITextList= {"Noun"}
machineUITextList= {"Pen","Box","Note","Scale"}
So my list i.e LineDashboardDetailList should give me output as:
Noun,Pen
Noun,Box
Noun,Note
Noun,Scale
I am using LineDashboardDetailList List further in my code.
Thanks in Advance.
I am not totally sure what you are trying to achive. Personally, I would use a java.util.Map to associate each value of the lineUITextList with the list of values of machineUITextList.
However, to help you in achiving your goal, first of all, I would design the LineDashboardDetails class in order to maintain the single value of the lineUITextList, along with the list of machineUITextList, so as you can combine them by using a specific method. That has lots of advantages in terms of encapsulation, distribution of responsabilities, etc.., plus you can always reuse for other purposes.
The function to combine the values can be easily implemented by taking advantages of Java stream and built-in functional interfaces.
Here is the code of the LineDashboardDetails class:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class LineDashboardDetails {
private String lineName;
private List<String> machineNames;
public String getLineName() {
return lineName;
}
public void setLineName(String lineName) {
this.lineName = lineName;
}
public List<String> getMachineNames() {
return new ArrayList<>(machineNames);
}
public void setMachineNames(List<String> machineNames) {
this.machineNames = new ArrayList<>(machineNames);
}
public List<String> getCombinedList() {
return machineNames.stream()
.map(s -> lineName + "," + s)
.collect(Collectors.toList());
}
}
Here is instead the code that you tried to implement, which uses the class above and combine the two list, and finally prints out the list of values as you expect. You can see, I prepared two simple list in the main method, but you can actually generalize it in relation to your own needs:
import java.util.List;
import java.util.ArrayList;
public class SeleniumWebdriverListTest {
public List<LineDashboardDetails> combineUITextListWithMachineUIText(List<String> lineUITextList,
List<String> machineUITextList) {
List<LineDashboardDetails> lineDashboardDetailList = new ArrayList<>();
for (String lineUIText : lineUITextList) {
LineDashboardDetails objLineDetail = new LineDashboardDetails();
objLineDetail.setLineName(lineUIText);
objLineDetail.setMachineNames(machineUITextList);
lineDashboardDetailList.add(objLineDetail);
}
return lineDashboardDetailList;
}
public static void main(String[] args) {
List<String> lineUITextList = new ArrayList<>();
lineUITextList.add("Noun");
List<String> machineUITextList = new ArrayList<>();
machineUITextList.add("Pen");
machineUITextList.add("Box");
machineUITextList.add("Note");
machineUITextList.add("Scale");
List<LineDashboardDetails> lineDashboardDetailList =
new SeleniumWebdriverListTest().combineUITextListWithMachineUIText(
lineUITextList, machineUITextList);
lineDashboardDetailList.stream()
.map(s -> s.getCombinedList())
.forEach(System.out::println);
}
}
I could have used Java streams and a specific lamba expression to implement the combineUITextListWithMachineUIText method as well, but I kept somehow your original version to let you understand my idea of implementation around your code.
Here is the output I get:
[Noun,Pen, Noun,Box, Noun,Note, Noun,Scale]
Feel free to ask for any clarification.
Question : How to remove all Strings in rayList that end with the same Last Letter as lastLetter?
I write my code like this so i remove all string from ArrayList that has same end character as lastLetter
import java.util.*;
public class LastLetter
{
public static ArrayList<String> go(ArrayList<String> rayList, char lastLetter)
{
ArrayList<String> result = new ArrayList<String>();
for(int i = 0; i<rayList.size(); i++)
{
char last = rayList.set(i, rayList.get(raylist.size() - 1));
if(lastLetter == last)
result.add(rayList.remove(i));
}
return result;
}
}
I do not know if it is working or not and i do not understand how to make runner for this code please correct any problems from my code and make a runner so we can run this code properly.
My try to make runner:
import java.util.*;
class Runner
{
public static void main(String[] args)
{
ArrayList<String> list = new ArrayList<String>();
list.add("fred");
list.add("at");
list.add("apple");
list.add("axe");
list.add("bird");
list.add("dog");
list.add("kitten");
list.add("alligator");
list.add("chicken");
LastLetter h = new LastLetter();
System.out.println(h.go(list),"m");
}
}
Please make a proper runner for this code.
Thank you
You should not remove elements while iterating the ArrayList, for more information read this post the simplest solution will be using removeif
rayList.removeIf(val-val.endsWith(String.valueOf(lastLetter)));
I would also suggest to take string as argument instead of char
public static ArrayList<String> go(ArrayList<String> rayList, String lastLetter) {
rayList.removeIf(val-val.endsWith(lastLetter));
return result;
}
And since go is static method in LastLetter class you can call it by using class name
LastLetter.go(Arrays.asList("My name is faheem"), "m");
I'm new to Java and I want to use one method, getCount, to get the sizes of two arraylists that are not the same size. What code could I use so that I can call, for example, examp1.getCount and examp2.getCount, and get the two different sizes?
This is frankly as basic a question as it gets, and google could have helped you with this easily. Here's your entire method if you want to design your own.
public static int getCount(ArrayList A){
return A.size();
}
In your method, use .size() to get the sizes of the two ArrayLists
and store the sizes in the array and then return that array.
Suppose you create 2 lists li1 and li2 then :
package output;
import java.util.ArrayList;
import java.util.List;
public class CalculateLength {
public static void main(String[] args) {
List<Integer> li1= new ArrayList<>();
li1.add(1);
li1.add(2);
getCount(li1);
List<Integer> li2= new ArrayList<>();
li2.add(1);
li2.add(2);
li2.add(3);
li2.add(4);
getCount(li2);
}
public static int getCount(List list) {
System.out.println("LEngth = " + list.size());
return list.size();
}
}
The problem is as follows:
6 words are to be displayed on the screen. These words are chosen at random from a list. When I wrote the code, I didn't get any error, but when I ran it in eclipse, I got the following gibberish result in the console "package.wordsContainer#659e0bfd".
What did I do wrong?
public class wordsContainer {
Collection<String> wordList = new ArrayList<String>();
public void wordGroup1() {
wordList.add("Ant");
wordList.add("Almond");
wordList.add("Atom");
wordList.add("Affair");
wordList.add("Ample");
wordList.add("Blue");
wordList.add("Black");
wordList.add("Bronze");
wordList.add("Beauty");
wordList.add("Beautiful");
wordList.add("Batter");
wordList.add("Crazy");
}
public Collection<String> getRandomWords() {
wordGroup1();
LinkedList<String> wordLinkedList = new LinkedList<String>(wordList);
ArrayList<String> subList = new ArrayList<String>();
int i = 0;
while (i < 6) {
int index = (int) Math.random() * 10;
if (!subList.contains(wordLinkedList.get(index))) {
subList.add(wordLinkedList.get(index));
i++;
}
}
return subList;
}
}
public class wordsContainerTest {
public static void main(String[] args) {
wordsContainer list1 = new wordsContainer();
list1.wordGroup1();
System.out.println(list1);
System.out.println(list1.getRandomWords());
}
}
It's not gibberish, hexadecimal representation of the hash code of the object wordsContainer
That result is from the line
System.out.println(list1); //wordsContainer
Not from ArrayList.
In order to work properly you need to override toString method in your class wordsContainer
To understand what exactly is "package.wordsContainer#659e0bfd" read the answer I wrote long back.
https://stackoverflow.com/a/17878495/1927832
Apart from that, please follow java naming conventions, Class names starts with Capital letter.
System.out.println(list1); //wordsContainer
You can't print out objects directly, you will just print out the reference to the place in memory where the object is saved, which is that weird output you are getting. You have to override the toString() method in your object or print out the properties of the object that you want individually.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class NNNTest {
private String SkillNeed="Java;C++;C";
private String SkillHave="SQL:8;Java:9;C++:5;C:9;PHP:5";
public boolean CheckAvailable(){
int flag=0;
int k;
String [] snar=SkillNeed.split(";");
String [] shandlevel=SkillHave.split(";");
for(int i=0;i<snar.length;i++){
for(k=0,flag=0;k<shandlevel.length;k++){
if(shandlevel[k].split(":")[0].equals(snar[i])){
System.out.println(shandlevel[k].split(":")[0]);
flag=1;
}
}
if(flag==0){
break;
}
}
if(flag==1){
System.out.println("YES");
return true;
}
else{
System.out.println("NO");
return false;
}
}
public static void main(String[] args) {
NNNTest n=new NNNTest();
n.CheckAvailable();
}
}
The method check if you have enough skills to acquire the job.
SkillNeed is a String that with form "skill;skill;skill....."
SkillHave is the skills and level you have and with form "skill:level;skill:level;...."
These are the codes that I typed,but I think it's pretty long and boring,do you have any other way to improve the method?Something like skipping the loop or Array or using java given methods.
Simply way with java-8:
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class NNNTest {
private static String skillNeed = "Java;C++;C"; //the skills the job need
private static String skillHave = "SQL:8;Java:9;C++:5;C:9;PHP:5"; //skill and level you have
public static boolean checkAvailable() { //if all the job needed skills match the skills you have
return Arrays.stream(skillHave.split(";")).map(s -> s.split(":")[0]).collect(Collectors.toSet()).containsAll(Arrays.asList(skillNeed.split(";")));
}
public static void main(String[] args) {
System.out.println(checkAvailable());
}
}
Edited for explanation:
Collect al skillHave in a Set (without the number).
Check if the Set of skillHave contains all elements of a given collection.
Collect all SkillNeed in another Set and pass it as parameter for previous step.
Another Java 8 Solution..
It basically iterates through all required skills and makes sure, using the allMatch() function, that each skill is contained in the givenSkills-String. Keep in mind, that you have to check for ":" aswell, otherwise "C" would also match "C++". This also makes sure, that it exactly matches the skill, since the skill is either at the beginning, or it is enclosed by ; and :.
public static boolean checkForRequiredSkills(String requiredSkills, String givenSkills)
{
return Arrays.stream(requiredSkills.split(";")).allMatch(skill -> givenSkills.startsWith(skill + ":") || givenSkills.contains(";" + skill + ":"));
}
A similar solution in earlier java versions could be looking like this
public boolean checkAvailable()
{
for (String skill : skillNeed.split(";"))
{
if (!skillNeed.startsWith(skill + ":") && !skillHave.contains(";" + skill + ":"))
return false;
}
return true;
}
Also the preferred idiom, to iterate over an Array or List is using a for-each loop..
for(String str : stringArray)
doSomething(str);