Check if lists contain same objects - java

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.

Related

How to check a treeset contains at least one items from another treeset

I have a treeset contains user selected items and I am trying to check with another base treeset which contains all items. If the user-selected set contains at leaset one item from base treeset, I should return true.
Here is my code:
Set<String> baseItems = new TreeSet<String>Arrays.asList("HEALTH","SPORTS","GAMES","COURSE","FITNESS"));
Set<String> userItems = getRequestedItems();
// userItems has values like HEALTH,SPORTS
// if userItems contains or match with any items in the baseItems list it should return true.
boolean isMatch = requestedApiPillars.contains(apiPillars); // this returning class cast exception.
How do I compare userSet with baseItems to make sure they selected the specific items?
You can use Collections.disjoint():
boolean isMatch = (! userItems.isEmpty()) && (! Collections.disjoint(baseItems, userItems));
Specifically, if at least one member of baseItems is also in userItems, the collections are not disjoint.

Is there a way to filter out the elements of a List containing object having a String element based on another List of String

I have a List of an object List<Object> which Objects contains String elements . Now There is also another List of String List<String> .
I want the first List to only contain objects which are elements of the second list.
What is the most efficient way to do this?
You can use the contains() method of the list and that's convenient in your case since it will equals() check the Strings.
e.g.
List<String> otherList = new ArrayList<>();
List<Object> test = new ArrayList<>();
Iterator<Object> it = test.iterator();
while(it.hasNext()){
if(!otherList.contains(it.next().getString())) it.remove();
}
or in Java8 streams
test.stream().filter(e -> otherList.contains(e.getString()))
.collect(Collectors.toList());
This will generate you a new List.

Comparing a string in a string object using 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

How to add to an arraylist of linkedlists?

I am sorry if this is a stupid question but I am new to Java linkedlists and arraylists.
What I wish to do is this:
I have a text file that I run through word for word. I want to create an Arraylist of linkedlists, which each uniqye word in the text followed in the linked list by the words that it is followed by in the text.
Consider this piece of text: The cat walks to the red tree.
I want the Arraylist of LinkedLists to be like this:
The - cat - red
|
cat - walks
|
to - the
|
red - tree
What I have now is this:
while(dataFile.hasNext()){
secondWord = dataFile.next();
nWords++;
if(nWords % 1000 ==0) System.out.println(nWords+" words");
//and put words into list if not already there
//check if this word is already in the list
if(follows.contains(firstWord)){
//add the next word to it's linked list
((LinkedList)(firstWord)).add(secondWord);
}
else{
//create new linked list for this word and then add next word
follows.add(new LinkedList<E>().add(firstWord));
((LinkedList)(firstWord)).add(secondWord);
}
//go on to next word
firstWord = secondWord;
}
And it gives me plenty of errors.
How can I do to this the best way? (With linkedlists, I know hashtables and binary trees are better but I need to use linked lists)
An ArrayList is not the best data structure for purpose of your outer list, and at least part of your difficulty stems from incorrect use of a list of lists.
In your implementation, presumably follows is an ArrayList of LinkedLists declared like this:
ArrayList<LinkedList<String>> follows = new ArrayList<>();
The result of follows.contains(firstWord) will never be true, because follows contains elements of type LinkedList, not String. firstWord is a String, and so would not be an element of follows, but would be the first element of an ArrayList which is an element of follows.
The solution offered below uses a Map, or more specifically a HashMap, for the outer list follows. A Map is preferable because when searching for the first word, the amortized look-up time will be O(1) using a map versus O(n) for a list.
String firstWord = dataFile.next().toLowerCase();
Map<String, List<String>> follows = new HashMap<>();
int nWords = 0;
while (dataFile.hasNext())
{
String secondWord = dataFile.next().toLowerCase();
nWords++;
if (nWords % 1000 == 0)
{
System.out.println(nWords + " words");
}
//and put words into list if not already there
//check if this word is already in the list
if (follows.containsKey(firstWord))
{
//add the next word to it's linked list
List list = follows.get(firstWord);
if (!list.contains(secondWord))
{
list.add(secondWord);
}
}
else
{
//create new linked list for this word and then add next word
List list = new LinkedList<String>();
list.add(secondWord);
follows.put(firstWord, list);
}
//go on to next word
firstWord = secondWord;
}
The map will look like this:
the: [cat, red]
cat: [walks]
to: [the]
red: [tree]
walks: [to]
I also made the following changes to your implementation:
Don't add duplicates to the list of following words. Note that a Set would be a more appropriate data structure for this task, but you clearly state that a requirement is to use LinkedList.
Use String.toLowerCase() to move all strings to lower case, so that "the" and "The" are treated equivalently. (Be sure you apply this to the initial value of firstWord as well, which doesn't appear in the code you provided.)
Note that both this solution and your original attempt assume that punctuation has already been removed.
You should not work using direct classes implementation, instead using their interfaces to ease the development (among other reasons). So, instead do the type casting every when and now, declare your variable as List and just define the class when initializing it. Since you haven't posted the relevant code to redefine it, I could give you an example of this:
List<List<String>> listOfListOfString = new LinkedList<>(); //assuming Java 7 or later used
List<String> listOne = new ArrayList<>();
listOne.add("hello");
listOne.add("world");
listOfListOfString.add(listOne);
List<String> listTwo = new ArrayList<>();
listTwo.add("bye);
listTwo.add("world");
listOfListOfString.add(listTwo);
for (List<String> list : listOfListOfString) {
System.out.println(list);
}
This will print:
[hello, world]
[bye, world]
Note that now you can change the implementation of any of listOne or listTwo to LinkedList:
List<String> listOne = new LinkedList<>();
//...
List<String> listTwo = new LinkedList<>();
And the code will behave the same. No need to do any typecast to make it work.
Related:
What does it mean to "program to an interface"?

Linked List of Linked Lists in Java

I would like to know how to create a linked list of linked lists. Also, It would be helpful if the predefined LinkedList (class from Java) and its methods are used for defining and for other add, get, listIterating operations.
You can put any object in a list, including another list.
LinkedList<LinkedList<YourClass>> list = new LinkedList<LinkedList<YourClass>>();
is a LinkedList of LinkedLists of YourClass objects. It can also be written in a simplified way since Java 7:
LinkedList<LinkedList<YourClass>> list = new LinkedList<>();
Very simple examples of manipulating such a list:
You then need to create each sublist, here adding a single sublist:
list.add(new LinkedList<YourClass>());
Then create the content objects:
list.get(sublistIndex).add(new YourClass());
You can then iterate over it like this (sublists' items are grouped by sublist):
for(LinkedList<YourClass> sublist : list) {
for(YourClass o : sublist) {
// your code here
}
}
If you want to add specific methods to this list of lists, you can create a subclass of LinkedList (or List, or any other List subclasses) or you can create a class with the list of lists as a field and add methods there to manipulate the list.
Well i've done this code and i've got it right
java.util.LinkedList mainlist = new java.util.LinkedList();
java.util.LinkedList sublist1 = new java.util.LinkedList();
sublist1.add(object1);
sublist1.add(object2);
sublist1.add(object3);
java.util.LinkedList sublist2=new java.util.LinkedList();
sublist2.add(1);
sublist2.add(2);
mainlist.add(sublist1);
mainlist.add(sublist2);
// To retrieve the sublist1 from mainlist...........
java.util.LinkedList temp = (java.util.LinkedList)mainlist.get(0);
Here variable mainlist is LinkedList of LinkedLists and variable temp contains the value the first list stored i.e sublist1..
You can even simplify access to the secondary lists, e.g. using
final List<List<String>> lists = new LinkedList<List<String>>() {
#Override
public List<String> get(final int index) {
while (index >= size()) {
add(new LinkedList<>());
}
return super.get(index);
}
};
This code automatically adds new LinkedLists to the outer list. With this code you can later easily add single values:
lists.get(2).add("Foo");
LinkedList<LinkedList<YourClass>> yourList = new LinkedList<LinkedList<YourClass>>();
As the declaration. To add another linked list (to the end by default) you would do
yourList.add(new LinkedList<YourClass>());
To add an element to lets say the second linked list in the series:
yourList.get(1).add(new YourClass());

Categories