find if ArrayList contains atleat one different string - java

I have an Arraylist of Strings that may or may not contain duplicates,
list = ["car", "car", "car"] OR list = ["car", "car", "bike", "car"]
I want to know something like below,
if(list contains All same strings)
same = true
else if(list contains atleast one different element)
same = false
Please help me out in writing above condition.

Put all values in a Set and check if size is 1 or more.
List<String> list = Arrays.asList("car", "car", "bike", "car");
Set<String> unique = new HashSet<String>(list);
boolean same;
if (unique.size() > 1) {
same = false;
} else {
same = true;
}
System.out.println(same); // prints false
System.out.println(list); // prints [car, car, bike, car]

If you are using Java 8 then this is very simple:
same = list.stream().distinct().count() > 1
If you are not familiar with streams, you can interpret this statement as: create a stream of the items in the list, filter out any duplicates and then count the number of unique items left in the stream.

containsAll() can check the list for whether all passed parameter is present or not. It accepts Collection type parameter as argument so make one more list pass only one parameter in that list and pass this as parameter to containsAll(). Following is dummy workable code
public static void main(String[] args)
{
List<String> list = new ArrayList<String>();
list.add("Car");
list.add("Car");
list.add("Car");
List<String> paramlist = new ArrayList<String>();
paramlist.add("Car");
boolean same = false;
if(list.containsAll(paramlist)){
same = true;
}
else{
same = false;
}
}

Related

What’s the best way to check if a list contains an item other than specified item?

Lets say I have a list and I want to search for an item with value “apple”.
List<String> items = new Arraylist<>():
I want to return false if items contains at least one element other than the item mentioned (“apple”), true if all items in the list are “apples”.
Here's a one-liner:
return items.stream().anyMatch(s -> !s.equals("apple"));
or cute but a little less obvious:
return items.stream().allMatch("apple"::equals);
With Stream IPA you can achieve that by using terminal operation allMath() that takes a predicate (function represented by boolean condition) and checks whether all elements in the stream match with the given predicate.
The code will look like that:
public static void main(String[] args) {
List<String> items1 = List.of("apple", "apple", "apple"); // expected true
List<String> items2 = List.of("apple", "orange"); // expected false
System.out.println(items1.stream().allMatch(item -> item.equals("apple")));
System.out.println(items2.stream().allMatch(item -> item.equals("apple")));
}
output
true
false
I use python but, I think is something like that:
list_entrance = input()
new_list = []
for cycle in list_entrance:
if cycle != "apple":
print("falce")
else:
continue
If you want of course you can "append" a items in "new_list".
I don't know full condition on your task.
Just to say your ArrayList should be defined like this:
List items = new ArrayList<>();
You missed out some caps in the question.
For the solution you could just loop through the list and check:
for (int x = 0; x<items.size(); x++){
if (! items.get(x).equals("apple")){
return false;
}
}
return true;
Instead use a Set, in order not to have duplicate items.
Collectors can also return Set:
Set<String> distinct = list.stream().collect(Collectors.toSet());

How can I can check if a value exists in an ArrayList?

try {
List<UpdateStockModel>
stockistIds=updateStockMapper.getStockInvoiceId(stockmodel);
String myList = new String();
for (UpdateStockModel x : stockistIds) {
//System.out.println("stockist list id.." + x.getStockInvoiceIds());
myList = myList.concat(x.getStockInvoiceIds());
myList = myList.concat(",");
}
List<String> list = new ArrayList<String>();
list.add(myList);
System.out.println("list.." + list);
System.out.println("stockInvoiceId is.." +
stockmodel.getStockInvoiceIds());
System.out.println("list status.." +list.contains(stockmodel.getStockInvoiceIds()));
if (list.contains(stockmodel.getStockInvoiceIds()) ==true){
return true;
} else {
return true;
}
}
Output:
list..[47,49,50,51,52,53,54,55,56,57,58,59,60,62,64,65,66,67,68,69,70,71,72,74,75,]
stockInvoiceId is..66
list status..false
return else
Here 66 existed in list but return false.I need to get true
Okay lets get it straight here.
You got a List full of objects which contain a ID.
You get the IDs from the object and concate them to a single large String.
Later on you add this single String to an ArrayList and expect the List.contains() method to find a proper match for you. This is not how it works.
You can either fix this, by calling list.get(0).contains(...) which will work since you will retrieve your string from the list and check it for the ID or even better,you add the Strings themself to an ArrayList.
Doing so would end up similiar to this:
List<UpdateStockModel>
stockistIds=updateStockMapper.getStockInvoiceId(stockmodel);
List<String> myList = new ArrayList<>();
for (UpdateStockModel x : stockistIds) {
myList.add(x.getStockInvoiceIds());
}
Doing so will replace the following part:
//This all becomes useless since you will already have a list with proper objects.
List<String> list = new ArrayList<String>();
list.add(myList);
System.out.println("list.." + list);
System.out.println("stockInvoiceId is.." +
stockmodel.getStockInvoiceIds());
System.out.println("list status.." +list.contains(stockmodel.getStockInvoiceIds()));
It's not rocket science.
Think of Lists as they were just more dynamic and flexible Arrays.
I think this is what you're after:
Set<String> ids = updateStockMapper.getStockInvoiceId(stockmodel)
.stream()
.map(usm -> usm.getStockInvoiceIds())
.collect(Collectors.toSet());
String id = stockmodel.getStockInvoiceIds();
return ids.contains(id);
Try to initalize the list as follows:
List<String> list = new ArrayList<String>();
for (UpdateStockModel x : stockistIds) {
//System.out.println("stockist list id.." + x.getStockInvoiceIds());
list.add(x.getStockInvoiceIds());
}
Then you can compare agains a list and not against a String.
// if the element that you want to check is of string type
String value= "66";// you use element instead of 66
Boolean flag=false;
if (list.contains(value)){
flag=true;
} else {
flag=false;
}
//you can use flag where you want
It looks like you setup the list varible as as an Arry with one entry.
replacing the statement
list.contains(..)
with
stockistIds.contains(..)
should do the trick.
The problem is in the if statement
Change:
if (list.contains(stockmodel.getStockInvoiceIds()) ==true){
return true;
} else {
return true;
}
to:
if (list.contains(stockmodel.getStockInvoiceIds()) ==true){
return true;
} else {
return false;
}

Create a Set of lists from two lists through recursion

I've searched through many questions on this site with somewhat similar underlying concepts, however after many hours of attempting to solve this problem myself and reviewing I am still lost. If there is another question that answers this I will be more than happy to give it a look over.
Ultimately I want to create a recursive method such that it takes two lists and returns a Set of String lists:
//Example of such a function definition
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo) {
}
When I say "Set of String lists" I mean specifically the following:
(Note:"AD" == "DA")
// if the two following lists are INPUTTED into myRecursiveMethod();
// listOne = ["A","B"]
// listTwo = ["C","D"]
// the following set is OUTPUTTED: [["AC","BD"],["AD","BC"]]
Such that if there were three elements in both listOne and listTwo, there would be SIX elements in the set. i.e:
// listOne = ["A","B","C"]
// listTwo = ["D","E","F"]
// OUTPUTTED: [["AD","BE","CF"],["AD","BF","CE"],["BD","AE","CF"],
// ["BD","AF","CE"],["CD","AE","BF"],["CD","AF","BE"]]
I tried writing this using a double enhanced FOR loop so I could understand the logic. My FOR loop approach is terrible and only works for the HARD-CODED limit of list.size() == 2.
// Create Lists and append elements
List<String> listOne = new ArrayList<String>();
listOne.add("A");
listOne.add("B");
List<String> listTwo = new ArrayList<String>();
listTwo.add("C");
listTwo.add("D");
// List One = ["A","B"]
// List Two = ["C","D"]
// Create new List
List<List<String>> newList = new ArrayList<List<String>>();
Integer counter = 0;
for (String s : listOne) {
counter++;
for (String p : listTwo) {
// A HARD-CODED bad implementation of this method
if (counter < 3) {
List<String> newListTwo = new ArrayList<String>();
newListTwo.add(s.concat(p));
newList.add(newListTwo);
} else if (!(counter % 2 == 0)) {
newList.get(1).add(s.concat(p));
} else {
newList.get(0).add(s.concat(p));
}
}
}
System.out.println(newList); // = [["AC","BD"],["AD","BC"]]
Also you can note that I defined List<List<String>> Rather than Set<List<String>>. This was due to my badly coded attempted which relies on the list.get() method.
So my current recursive method is as follows:
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo)
{
//Base Case:
if (listOne.isEmpty){
return new HashSet<List<String>>;
}
//Recursive Case:
else {
String listOneFirst = listOne.get(0);
String listTwoFirst = listTwo.get(0);
List<String> sampleList = new ArrayList<String>();
sampleList.add(listOneFirst+listTwoFirst);
Set<List<String>> newSet = new HashSet<List<String>>(myRecursiveMethod())
newSet.add(sampleList);
return newSet;
}
}
This method only acts like this currently:
INPUT:
List One = ["A","B"]
List Two = ["C","D"]
OUTPUT:
[["AC"]["BD"]]
DESIRED OUTPUT:
[["AC","BD"],["AD","BC"]]
EDIT:
After reviewing responses my W.I.P code for the class:
private static Set<List<String>> myRecursiveMethod(List<String> listOne,
List<String> listTwo) {
//Backup Case (user enters an empty list)
if (listOne.isEmpty()){
return new HashSet<List<String>>();
}
// Base Case:
if (listOne.size() == 1) {
List<String> mergedStrings = new ArrayList<>();
for (String s : listTwo) {
mergedStrings.add(listOne.get(0).concat(s));
}
Set<List<String>> builtHashSet = new HashSet<List<String>();
builtHashSet.add(mergedStrings);
return builtHashSet;
}
// Recursive Case:
else {
// Ensure original list values arn't changed.
List<String> newListOne = new ArrayList<String>(listOne);
List<String> newListTwo = new ArrayList<String>(listTwo);
//first two elements...I don't think this is correct
String listOneFirst = newListOne.get(0);
String listTwoFirst = newListTwo.get(0);
List<String> sampleList = new ArrayList<String>();
sampleList.add(listOneFirst + listTwoFirst);
//used for making recursive case smaller
newListOne.remove(0);
// Calls recursion
Set<List<String>> newSet = new HashSet<List<String>>(
myRecursiveMethod(newListOne, newListTwo));
newSet.add(sampleList);
return newSet;
}
}
I think the problem is here:
if (listOne.isEmpty){
return new HashSet<List<String>>;
}
You are correct, at some point your recursion has to end, and you have to start building the desired output. But the desired output is not a Set with an empty list. It is a Set containing some lists with some content. Thus: don't wait until listOne is empty. Instead:
if (listOne.size() == 1) {
List<String> mergedStrings = new ArrayList<>();
mergedStrings = ... merge the ONE listOne entry with all listTwo entries
Set<List<String>> rv = new HashSet<>();
rv.add(mergedStrings);
return rv;
}
In other words: you use recursion to reduce the length of the first list by one. And when only one element is left in that list, it is time to merge in the second list.
Now lets look into how to "use" that (calling the method rec for brevity); putting down some pseudo code to show the steps we need:
rec([a, b], [c,d]) -->
rec([a], [c,d]) X rec([b], [c, d]) -->
<[ac, ad]> X <[bc, bd]> -->
<[ac, ad], [bc, bd]>
"X" meaning "joining" two results from recursive calls; should be as easy as:
Set<List<String>> rec1 = rec(...);
return rec1.addAll(rec2 ...

Java - Comparing a single String value with all the String values in an ArrayList

I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do
that in Java?
For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".
I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.
I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems
to be working. I was just wondering whether there is any simple way to achieve this.
That's simple with Java 8:
String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
For Java 7 replace the last line with:
boolean allMatch = true;
for (String string : strings) {
if (!string.equals(str)) {
allMatch = false;
break;
}
}
If you want to know if the array contains the string use ArrayList::contains()
String s = "HI";
ArrayList<String> strings = // here you have your string
if (string.contains(s)) {
// do your stuff
}
If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.
boolean areSame = true;
for (String str : strings) {
if (!str.equals(s)) areSame = false;
}
if (areSame) {
// all elements are same
}
1) You can the pass the arraylist into a set.
2) Now you can get the size of set, if it is equal to 1 that means all elements are same.
3) Now you can use the contains on set to check if your value is present in it or not.
public static void main(String[] args){
String toBeCompared="foo";
List<String> list=new ArrayList<String>();
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
Set<String> set=new HashSet<String>(list);
if(1==set.size()){
System.out.println(set.contains(toBeCompared));
}
else{
System.out.println("List has different values");
}
}
You can use this method to do that
private boolean allAreSame(ArrayList<String> stringList, String compareTo){
for(String s:stringList){
if(!s.equals(compareTo))
return false;
}
return true;
}
I would do it like this:
ArrayList<String> foos = new ArrayList<>();
String str = "foo";
for (String string : foos) {
if(string.equals(str)){
System.out.println("True");
}
}

removing duplicates from list of lists and preserving lists

I have an arrayList of arrayLists. Each inner arraylist contains some objects with the format (name.version) .
{ {a.1,b.2,c.3} , {a.2,d.1,e.1} , {b.3,f.1,z.1}....}
For example a.1 implies name = a and version is 1.
So i want to eliminate duplicates in this arraylist of lists. For me , two objects are duplicate when they have the same name
So essentially my output should be
{ { a.1,b.2,c.3},{d.1,e.1} ,{f.1 ,z.1} }
Note that i want the output in the exact same form (That is , i dont want a single list with no duplicates)
Can someone provide me with an optimal solution for this?
I can loop through each inner list and place the contents in the hashset. But two issues there, i cant get back the answer in
form of list of lists.Another issue is that when i need to override equals for that object , but i am not sure if that would
break other code. These objects are meaningfully equal if their names are same (only in this case. I am not sure that would
cover the entire spectrum)
Thanks
I used Iterator.remove() to modify the collection as you move through it.
// build your example input as ArrayList<ArrayList<String>>
String[][] tmp = { { "a.1", "b.2", "c.3" }, { "a.2", "d.1", "e.1" },
{ "b.3", "f.1", "z.1" } };
List<List<String>> test = new ArrayList<List<String>>();
for (String[] array : tmp) {
test.add(new ArrayList<String>(Arrays.asList(array)));
}
// keep track of elements we've already seen
Set<String> nameCache = new HashSet<String>();
// iterate and remove if seen before
for (List<String> list : test) {
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String element = it.next();
String name = element.split("\\.")[0];
if (nameCache.contains(name)) {
it.remove();
} else {
nameCache.add(name);
}
}
}
System.out.println(test);
Output
[[a.1, b.2, c.3], [d.1, e.1], [f.1, z.1]]
List<List<Pair>> inputs; // in whatever format you have them
List<List<Pair>> uniqued = new ArrayList<>(); // output to here
Set<String> seen = new HashSet<String>();
for (List<Pair> list : inputs) {
List<Pair> output = new ArrayList<>();
for (Pair p : list)
if (seen.add(p.getName()))
output.add(p);
uniqued.add(output);
}
Create a Set. Iterate over the list of lists' items. See if the item is in the Set. If it is already there, ignore it. If it isn't, add it to the Set and the list of lists.
Your method will return a new list of lists, not modify the old one. Modifying a list while iterating over it is a pain.

Categories