Comparing a string in a string object using java - java

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

Related

Check if lists contain same objects

I have two filled lists.
The first list contains for example:
"Shoppinglist-fruit", "Shoppinglist-drinks", "Shoppinglist-dinner"
The second list contains:
"Shoppinglist-drinks"
Now i wanna print all items in the first list, except if there's a same object in the second list with the same name (Shoppinglist-drinks).
Looking like:
"Shoppinglist-fruit", "Shoppinglist-dinner"
So how can i check if the name of the object inside the second list is also in one of the objects of the first list.
Eventually i want to end up with a string containing all the names of the shoppinglists that are in the first list and not in the second one.
I started with some code below but i haven't been able to finish it.
I have the two lists, one called listShoppinglists, this is a list filled with different shopping lists.
And the second list filled with somebody's shoppinglists.
So i wanna check if the name of the shoppinglists are equal.
If done that by doing so.
public String getAllShoppingLists(List listShoppinglists, Customer customer, List shoppinglists) {
String namesOfTheShoppingListNames = ""
for (Shoppinglist shoppinglist : listShoppinglists) {
for (int i = 0; i < customer.shoppinglists.size(); i++) {
if (customer.shoppinglists.get(i).getName().equals(shoppinglist.getName())) {
// Some action here
}
}
}
return namesOfTheShoppingListNames;
}
You can try this:
List<ShoopingList> firstShoppingListNames = new ArrayList<>();
firstShoppingListNames.add(new ShoppingList("fruit"));
firstShoppingListNames.add(new ShoppingList("dinner"));
firstShoppingListNames.add(new ShoppingList("juice"));
List<ShoppingList> secondShoppingListNames = new ArrayList<>();
secondShoppingListNames.add(new ShoppingList("fruit"));
List<ShoppingList> distinct = firstShoppingListNames.stream().
filter( list -> secondShoppingListNames.stream().
noneMatch(o -> o.getName().equals(list.getName()))).
collect(Collectors.toList());
distinct.forEach(o -> System.out.print(o.getName()));
In this case you are using stream to achieve what you want. You filter first list to obtain those elements, which are not present in other list.
Additionaly if you want to obtain only names of those lists you can use map:
List<String> distinct = firstShoppingListNames.stream().
filter( list -> secondShoppingListNames.stream().
noneMatch(o -> o.getName().equals(list.getName()))).
map(ShoppingList::getName).collect(Collectors.toList());
Use Collections.removeAll() method to do this. Quoted from JavaDoc:-
Removes all of this collection's elements that are also contained in
the specified collection (optional operation). After this call
returns, this collection will contain no elements in common with the
specified collection
.List<String> list1=new ArrayList<String>();
list1.add("Shoppinglist-fruit");list1.add("Shoppinglist-drinks");list1.add("Shoppinglist-dinner");
List<String> list2=new ArrayList<String>();
list2.add("Shoppinglist-drinks");
list1.removeAll(list2);
System.out.println(list1);
//Output:- [Shoppinglist-fruit, Shoppinglist-dinner]
In case, lists contains a custom objects, override equals and hashcode methods in that custom object.

How to use hamcrest contains to compare 2 lists?

Why does this test fail? I know contains works when you pass in individual strings separated by commas but I wanted to see if it's possible to just pass in an entire list of strings instead. I just want to make sure that list 1 contains all of the contents of list 2.
#Test
public void testContains() {
String expected1 = "hello";
String expected2 = "goodbye";
List<String> expectedStrings = new ArrayList<>();
expectedStrings.add(expected1);
expectedStrings.add(expected2);
List<String> actualStrings = new ArrayList<>();
actualStrings.add(expected1);
actualStrings.add(expected2);
assertThat(actualStrings, contains(expectedStrings));
}
Is it considered acceptable to use this assertion instead?
assertThat(actualStrings, is(expectedStrings));
There is no overloaded contains method which takes a list of expected values.
In the statement assertThat(actualStrings, contains(expectedStrings))
the following method (in the Matchers class) is called:
<E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(E... items)
Basically you are saying that you expect a list with one element and this element is expectedStrings but in fact it is expected1 (E is of type List<String> and not String). To verify add the following to the test which should then pass:
List<List<String>> listOfactualStrings = new ArrayList<>();
listOfactualStrings.add(actualStrings);
assertThat(listOfactualStrings, contains(expectedStrings));
To make the assertion work you have to convert the list to an array:
assertThat(actualStrings, contains(expectedStrings.toArray()));
If you want to apply a matcher for each item in a list you can use the everyItem matcher, like so:
everyItem(not(isEmptyOrNullString()))

Comparing string against arraylist

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
}
}

Get unique values from ArrayList in Java

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.

remove duplicates from object array data java

i want to know how to remove duplicates in object.
for example
cat c[] = new cat[10];
c[1].data = "ji";
c[2].data = "pi";
c[3].data = "ji";
c[4].data = "lp";
c[5].data = "ji";
c[6].data = "pi";
c[7].data = "jis";
c[8].data = "lp";
c[9].data = "js";
c[10].data = "psi";
i would like to remove the duplicates value from object array.
thanks and advance
I assume you want to create another array which is duplicate free. (as you cannot change the size of an array)
You could implement hashCode and equals and use a HashSet, however without these you can create a Comparator.
However the simplest approach may be using the "Cat" class and "cats" array
Cat[] cats = { ... };
Set<String> datas = new HashSet<String>();
List<Cat> catList = new ArrayList<Cat>();
for(Cat cat: cats) if(datas.add(cat.data)) catList.add(cat);
Cat[] unqiueCats = catList.toArray(new Cat[catList.size()]);
Something like this should work? Make sure to import java.util.Arrays and java.util.HashSet.
/**
* Removes duplicates from an array. Objects in the array must properly
* implement hashCode() and equals() for this to work correctly.
*/
public static <E> E[] removeDuplicates(E[] array) {
// convert input array to populated list
List<E> list=Arrays.asList(array);
// convert list to populated set
HashSet<E> set=new HashSet<E>();
set.addAll(list);
// convert set to array & return,
// use cast because you can't create generic arrays
return (E[]) set.toArray();
}
You can create another temporary array, loop through the original array, and for each element, check if the value already in the temp array or not. If not, add it in.
You can also use Set and override the equals and hashCode method
Here's a quick hack to do what you wanted to (hopefully also compiles):
// Assuming the code in the question is here.
java.util.List<cat> tmp = new java.util.LinkedList<cat>();
java.util.HashSet<String> set = new HashSet<String>();
for (int i = 0; i < c.length; ++i)
if (set.put(c[i].data)) tmp.add(c[i]);
c = tmp.toArray(c);

Categories