I have an arrayList which I need to compare against String.
What I have done:
ArrayList<String> val = new ArrayList<String>();
val= getValues();
If I print val , it gives me expected values.But
if(val.contains("abcd"))
It is returning false although at time of printing values of val it consists of abcd.
What can possibly be wrong?
Edited:
How my arraylist is getting values:
IOUtils.copy(inputStream , write)
str = write.toString()
ArrayList<String> list = new ArrayList<String>();
list.addAll(Arrays.asList(str));
return list;
you need to make sure that val contains string exactly as abcd(no space, no uppercase). But if it is not case-sensitive and you allow space, then you may check it like this:
boolean isExist = false;
for(int i=0;i<val.size();i++){
if(val.get(i).trim().toLowerCase().equals("abcd")){
isExist=true;
break;
}
}
If getValues() returns an arraylist of strings, you need to ensure that the string "abcd" is exactly as given in parameter. Also since according to the docs, the contains method implements the equals method for comparison, you should make sure that the string has the right case as equals is case sensitive.
contain() method works by comparing elements of Arraylist on equals() method. If your arraylist has "abcd", it should return 'true'. Try checking if your getValues() method returns some hidden character/space along with "abcd".
do something like below.
for(int i=0;i<val.size();i++){
if(val.get(i).contains("abcd") || val.get(i).contains("ABCD")){
// do some thing here
}
}
Related
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
is there any way in java that i can check a list of words to see if a variable matches any of them, and if it does I want to increment a counter. I know I create a lot of if statements but I think a list of some sort would make the program easier to navigate.
For example if variable 1 is equal to any in the list increment positive value.
String vbl1 = "happy";
then i would have a few lists like:
list 1:
joyful
great
excited
happy
thanks in advance guys.
Use java.util.List or any other datastructure that implements java.util.Collection. As suggested in comments, java.util.Set may suit better if ordering does not matter.
You can check if a given items exists in the list by using contains() method.
List<String> list = new ArrayList<>();
list.add("joyful");
list.add("great");
list.add("excited");
list.add("happy");
boolean contains = list.contains("happy");
Ignoring case you can do
list.contains(yourWord)
This will return true if there is a match so you can increment your counter then.
If you want to consider case I think the clearest way will be to loop through the list and calling equals on each item in the list
Edit: as per comment in another answer a set may be cleaner and more efficient as it will remove any duplicates you have in your list (although won't guarantee an order
)
Yes, perhaps with something like this
public static void main(String[] args) {
String[] words = { "joyful", "great", "excited",
"happy" };
java.util.List<String> list1 = java.util.Arrays
.asList(words);
String vbl1 = "happy";
if (list1.contains(vbl1)) {
System.out.printf("%s contains %s\n",
java.util.Arrays.toString(words), vbl1);
} else {
System.out.printf("%s does not contain %s\n",
java.util.Arrays.toString(words), vbl1);
}
}
Which outputs
[joyful, great, excited, happy] contains happy
String[] words = { "joyful", "great", "excited","happy" };
String matchStr = "happy";
for(String i:words){
if(i.equals(matchStr)){
// Increment Counter Here
}
}
I am a writing a class that whose constructor takes an List<String> and returns a hashmap having length of string as key(Integer) and its value as arrayList<String> that holds string.
That is I am trying to map length of strings to list of strings. Here is my code.
public class Solver {
Map<Integer,ArrayList<String>> inventoryMap;
//constructor
public Solver(List<String> list){
inventoryMap=new HashMap<Integer,ArrayList<String>>();
for (String s : list) {
int x = s.length();
if (inventoryMap.containsKey(x)){
inventoryMap.put(x,inventoryMap.get(x).add(s));
} else {
newlist=new ArrayList<String>();
newlist.add(s);
inventoryMap.put(x,newlist);
}
}
}
when I complile this code, I get the following error
Solver.java:12: put(java.lang.Integer,java.util.ArrayList<java.lang.String>) in java.util.Map<java.lang.Integer,java.util.ArrayList<java.lang.String>> cannot be applied to (int,boolean)
inventoryMap.put(x,inventoryMap.get(x).add(s));
I think I am going wrong in adding String elements to my ArrayList<String> which is value of Map
can you guide me with what I could possibly be going wrong?
if (inventoryMap.containsKey(x)) {
inventoryMap.put(x,inventoryMap.get(x).add(s));
}
Change this with
if (inventoryMap.containsKey(x)) {
inventoryMap.get(x).add(s);
}
Reason is inventoryMap.get(x).add(s) will return boolean so you cann't put boolean in place of List.
As map already contains list so adding any element in a list you need not to put any entry in a map. Just get the list from map and add element to it.
inventoryMap.get(x).add(s) returns boolean and you tried to put it in the map. This is the cause of the exception. Put the list in the map will resolve the issue.
Your code inventoryMap.get(x).add(s) adds the value to the list and return a boolean.
So You need to have something like.
List<String> list =inventoryMap.get(x);
list.add(s);
You cannot chain your method calls like inventoryMap.put(x,inventoryMap.get(x).add(s)) since add returns a boolean. As a matter of fact, you don't even need the put statement. Since you aren't removeing the List, its reference will stay in the Map so any updates to the List will be visible.
All you need is inventoryMap.get(x).add(s).
First of all inventoryMap.get(x).add(s) returns boolean(whether elements where successfully added or not ). So is incompatible with the type ArrayList<String>. You can simple do
inventoryMap.get(x).add(s)
No need to explicitly call pur() function.
Secondly int x = s.length(); should be Integer x = s.length();. You can put int where Integer is expected(anyways you cannot use int in generics).
The problem with this line
inventoryMap.put(x,inventoryMap.get(x).add(s));
is that inventoryMap.get(x).add(s) will return a boolean and map expects a List here. You need to break down this statement. something like this:
List<String> stirngsList = inventoryMap.get(x);
stirngsList.add(s);
I have an ArrayList with a number of records and one column contains gas names as CO2 CH4 SO2, etc. Now I want to retrieve different gas names(unique) only without repeatation from the ArrayList. How can it be done?
You should use a Set. A Set is a Collection that contains no duplicates.
If you have a List that contains duplicates, you can get the unique entries like this:
List<String> gasList = // create list with duplicates...
Set<String> uniqueGas = new HashSet<String>(gasList);
System.out.println("Unique gas count: " + uniqueGas.size());
NOTE: This HashSet constructor identifies duplicates by invoking the elements' equals() methods.
You can use Java 8 Stream API.
Method distinct is an intermediate operation that filters the stream and allows only distinct values (by default using the Object::equals method) to pass to the next operation.
I wrote an example below for your case,
// Create the list with duplicates.
List<String> listAll = Arrays.asList("CO2", "CH4", "SO2", "CO2", "CH4", "SO2", "CO2", "CH4", "SO2");
// Create a list with the distinct elements using stream.
List<String> listDistinct = listAll.stream().distinct().collect(Collectors.toList());
// Display them to terminal using stream::collect with a build in Collector.
String collectAll = listAll.stream().collect(Collectors.joining(", "));
System.out.println(collectAll); //=> CO2, CH4, SO2, CO2, CH4 etc..
String collectDistinct = listDistinct.stream().collect(Collectors.joining(", "));
System.out.println(collectDistinct); //=> CO2, CH4, SO2
I hope I understand your question correctly: assuming that the values are of type String, the most efficient way is probably to convert to a HashSet and iterate over it:
ArrayList<String> values = ... //Your values
HashSet<String> uniqueValues = new HashSet<>(values);
for (String value : uniqueValues) {
... //Do something
}
you can use this for making a list Unique
ArrayList<String> listWithDuplicateValues = new ArrayList<>();
list.add("first");
list.add("first");
list.add("second");
ArrayList uniqueList = (ArrayList) listWithDuplicateValues.stream().distinct().collect(Collectors.toList());
ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique
Here's straightforward way without resorting to custom comparators or stuff like that:
Set<String> gasNames = new HashSet<String>();
List<YourRecord> records = ...;
for(YourRecord record : records) {
gasNames.add(record.getGasName());
}
// now gasNames is a set of unique gas names, which you could operate on:
List<String> sortedGasses = new ArrayList<String>(gasNames);
Collections.sort(sortedGasses);
Note: Using TreeSet instead of HashSet would give directly sorted arraylist and above Collections.sort could be skipped, but TreeSet is otherwise less efficent, so it's often better, and rarely worse, to use HashSet even when sorting is needed.
When I was doing the same query, I had hard time adjusting the solutions to my case, though all the previous answers have good insights.
Here is a solution when one has to acquire a list of unique objects, NOT strings.
Let's say, one has a list of Record object. Record class has only properties of type String, NO property of type int.
Here implementing hashCode() becomes difficult as hashCode() needs to return an int.
The following is a sample Record Class.
public class Record{
String employeeName;
String employeeGroup;
Record(String name, String group){
employeeName= name;
employeeGroup = group;
}
public String getEmployeeName(){
return employeeName;
}
public String getEmployeeGroup(){
return employeeGroup;
}
#Override
public boolean equals(Object o){
if(o instanceof Record){
if (((Record) o).employeeGroup.equals(employeeGroup) &&
((Record) o).employeeName.equals(employeeName)){
return true;
}
}
return false;
}
#Override
public int hashCode() { //this should return a unique code
int hash = 3; //this could be anything, but I would chose a prime(e.g. 5, 7, 11 )
//again, the multiplier could be anything like 59,79,89, any prime
hash = 89 * hash + Objects.hashCode(this.employeeGroup);
return hash;
}
As suggested earlier by others, the class needs to override both the equals() and the hashCode() method to be able to use HashSet.
Now, let's say, the list of Records is allRecord(List<Record> allRecord).
Set<Record> distinctRecords = new HashSet<>();
for(Record rc: allRecord){
distinctRecords.add(rc);
}
This will only add the distinct Records to the Hashset, distinctRecords.
Hope this helps.
public static List getUniqueValues(List input) {
return new ArrayList<>(new LinkedHashSet<>(incoming));
}
dont forget to implement your equals method first
If you have an array of a some kind of object (bean) you can do this:
List<aBean> gasList = createDuplicateGasBeans();
Set<aBean> uniqueGas = new HashSet<aBean>(gasList);
like said Mathias Schwarz above, but you have to provide your aBean with the methods hashCode() and equals(Object obj) that can be done easily in Eclipse by dedicated menu 'Generate hashCode() and equals()' (while in the bean Class).
Set will evaluate the overridden methods to discriminate equals objects.
I have LinkedHashMap<String,ArrayList<String>> h
If I do this: System.out.println(h.get("key1")); it prints out this: [Burger King]
But if I do this:
if (h.get("key1").contains("Burger"))
System.out.println("Key1 contains Burger");
It ignores it. How do I check for a particular string in the ArrayList of the associated key?
ArrayList.contains() Returns true if this list contains the specified element.
In your case it doesn't contain "Burger", but it contains "Burger King", the matching is identical not on subtrings.
To achieve what you want you've to loop on the ArrayList and check each element with String.contains() applied on the String which is defined as "Returns true if and only if this string contains the specified sequence of char values".
If you want also to ignore the case you can apply String.toLowerCase() to your search term and to each element before applying String.contains().
you are testing a list for inclusion of a partial string, which will not work, since the actual values is "Burger King". You need to call contains() on each element of the ArrayList if you want to check for a partial match.
List.contains() looks for an exact matching element.
Do you mean this?
for(String s: results.get("key1"))
if(s.contains("Burger"))
System.out.println("Key1 contains Burger");
You have to iterate over all String objects in the ArrayList<String> and call their contains() method:
boolean containsSubString(final Collection<String> strings, final String searchString) {
for (String s : strings) {
if (s.contains(searchString)) {
return true;
}
}
return false;
}
The List contains the String Burger King and you are looking for the String Burger. Hence no output.