Trying to compare each element of two different ArrayLists - java

So I need to compare two different ArrayLists elements. If the element from the first ArrayList(tweets) does not match any from the second(hashTags) I want to add the element(from tweets) to the second ArrayList(hashTags)
Here is my code thus far:
package edu.bsu.cs121.albeaver;
import java.util.*;
public class HashTagCounter {
public static void main(String args[]) {
System.out
.println("Please tweet your tweets,and type 'done' when you are done.");
Scanner twitterInput = new Scanner(System.in);
ArrayList<String> tweets = new ArrayList<String>();
ArrayList<String> hashTags = new ArrayList<String>();
while (true) {
String tweet = twitterInput.next();
tweets.add(tweet);
if ("done".equals(tweet))
break;
}
System.out.println(tweets);
twitterInput.close();
int count = 0;
for (String tweet : tweets) {
if (tweet.contains("#") && count == 0) {
hashTags.add(tweet);
hashTags.add(1, "");
count++;
} else if (tweet.contains("#")) {
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
}
}
System.out.println(hashTags);
System.out.println("Number of unique '#' used is: "
+ (hashTags.size() - 1));
}
}
(edit)I seem to get a 'java.util.ConcurrentModificationException' error.
Thank you for any and all help:)

for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
-----------------------------^
}
}
The issue is while iterating the hashTags list you cant update it.

You are getting java.util.ConcurrentModificationException because you are modifying the List hashTags while you are iterating over it.
for (String hashTagged : hashTags) {
if (tweet.equalsIgnoreCase(hashTagged) != true) {
hashTags.add(hashTagged);
}
}
You can create a temporary list of items that must be removed or improve your logic.

Related

How to set two Java Arraylist values into one Java object?

I have an issue while working with java ArrayList. Here is the brief description:
By making a web service call, I will get all the videos around 900+ as Java objects. These Java objects are lacking some of the required information. So I am again making a call to another web service by passing the video id. This also returns Java objects.
I am storing the first web service call values and the second web service call values into two different Java ArrayLists as below:
List mediaList = new ArrayList();
List mediaVOs = new ArrayList();
Finally I am writing a method by passing two lists and setting those values into one java object. This should return the total objects around 942. But this is returning some odd number 887364 instead of 942 count.
Please help me resolving the issue. Here is the code:
client = getClient();
if (client != null) {
List<MediaEntry> mediaList = getAllMedia();
if (mediaList.size() >= 1) {
System.out.println("Total Media ------>" + mediaList.size());
MetadataListResponse metadataListResponse = null;
Media mediaVO = null;
List<List<String>> metadataValues = new ArrayList<List<String>>();
List<String> categoriesList = new ArrayList<String>();
List<String> accountNamesList = new ArrayList<String>();
List<String> ownerNamesList = new ArrayList<String>();
List<String> countryList = new ArrayList<String>();
List<String> languageList = new ArrayList<String>();
for(MediaEntry entry:mediaList) {
if(entry != null) {
metadataListResponse = getMetadata(entry.id);
if (metadataListResponse.totalCount >= 1) {
mediaVO = new Media();
List<Metadata> metadataObjs = metadataListResponse.objects;
if (metadataObjs != null
&& metadataObjs.size() > 0) {
for (int i = 0; i < metadataObjs.size(); i++) {
Metadata metadata = metadataObjs
.get(i);
if (metadata != null) {
if (metadata.xml != null) {
metadataValues = parseXml(metadata.xml);
if (metadataValues.size() != 0) {
categoriesList = metadataValues
.get(0);
accountNamesList = metadataValues.get(1);
ownerNamesList = metadataValues.get(2);
countryList = metadataValues.get(3);
languageList = metadataValues.get(4);
if (categoriesList.size() == 1) {
for (String categoryName : categoriesList) {
//System.out
//.println("categoryName"+categoryName);
mediaVO.setCategories(categoryName);
}
}
if (accountNamesList.size() == 1) {
for (String accountName : accountNamesList) {
//System.out
//.println("accountName"+accountName);
mediaVO.setAccountName(accountName);
}
}
if (ownerNamesList.size() == 1) {
for (String ownerName : ownerNamesList) {
//System.out
//.println("ownerName"+ownerName);
mediaVO.setOwnerName(ownerName);
}
}
if (countryList.size() == 1) {
for (String country : countryList) {
//System.out
//.println("country"+country);
mediaVO.setCountry(country);
}
}
if (languageList.size() == 1) {
for (String language : languageList) {
//System.out
//.println("language"+language);
mediaVO.setLanguage(language);
}
}
}
}
}
}
}
}
mediaVOs.add(mediaVO);
}
}
System.out.println("mediaVOs.size()------>"+mediaVOs.size());
List<Media> medias = setMediaVO(mediaList, mediaVOs);
if(medias.size() >= 1) {
System.out.println("Final medias size ------>"+medias.size());
mediaXml = convertToXml(medias);
System.out.println("Final Media XML converted ------->"+mediaXml);
Document doc = convertStrToDoc(mediaXml);
}
}
}
private List<Media> setMediaVO(List<MediaEntry> mediaList,List<Media> mediaList1) {
if(mediaList.size() >= 1) {
if(mediaList1.size() >= 1) {
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
Media mediaVO = new Media();
MediaType mediaType = media.mediaType;
mediaVO.setMediaId(media.id);
mediaVO.setMediaName(media.name);
mediaVO.setMediaDesc(media.description);
mediaVO.setCreatedDate(media.createdAt);
mediaVO.setCreditUserName(media.creditUserName);
mediaVO.setDataUrl(media.dataUrl);
mediaVO.setDownloadUrl(media.dataUrl);
mediaVO.setDuration(media.duration);
mediaVO.setEndDate(media.endDate);
mediaVO.setEntitledUsersEdit(media.entitledUsersEdit);
mediaVO.setEntitledUsersPublish(media.entitledUsersPublish);
mediaVO.setLastPlayedAt(media.lastPlayedAt);
mediaVO.setMediaType(mediaType.toString());
mediaVO.setUpdatedDate(media.updatedAt);
mediaVO.setPlays(media.plays);
mediaVO.setViews(media.views);
mediaVO.setCategories(media1.getCategories());
mediaVO.setAccountName(media1.getAccountName());
mediaVO.setOwnerName(media1.getOwnerName());
mediaVO.setCountry(media1.getCountry());
mediaVO.setLanguage(media1.getLanguage());
medias.add(mediaVO);
}
}
}
}
return medias;
}
Thanks,
Raji
Your problem is here :
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
For each MediaEntry, you're looping on each Media, which means you'll execute the code inside 942 * 942 times, while what you want is to execute it 942 times. You've got to match MediaEntries with Media and execute the code once.
Let me try to explain this in a way where everybody understands what i mean.
The problem is indeed the fact that you multiply 942 by itself.
This happens cause of the following code:
private List<Media> setMediaVO(List<MediaEntry> mediaList,List<Media> mediaList1) {
if(mediaList.size() >= 1) {
if(mediaList1.size() >= 1) {
for(MediaEntry media:mediaList) {
for(Media media1:mediaList1) {
//Do stuff
}
}
}
}
return medias;
}
Here you loop though medialist 1 for each item in medialist and do stuff with it.
At the end of this code you add each entry found in medialist 1 to a other list but this happend 942 times per item in the first list.
And since that list has 942 items you get the "odd" number of 887.364.

Add the items from one list to another list in java

I have two arraylists say
ArrayList<BaseItem> normal;
ArrayList<BaseItem> highlighted;
normal = new ArrayList<BaseItem>();
highlighted = new ArrayList<BaseItem>();
what I am doing is I am Iterating through a 3rd list(called MyItems) and adding the items in it called highlight and normal to the above two lists like this.
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highlighted.add(itemtype);
}
else{
normal.add(itemtype);
}
}
So my question is I want to add every 5th and 6th item of the highlited list to the list called normal .i.e elements like 5,6,11,12,17,18 and so on
and also I want to add every 6th and 7th item of normal list to highlighted list i.e 6,7,13,14 and so on.
so now my highlighted and normal lists will contain the items like this
Highlighted -> highlighted1,highlighted2,highlighted3,highlighted4,normal6,normal7 highlighted7,highlighted8.highlighted9,highlighted10,normal13,normal14 and so on
Normal -> Noraml1,normal2,normal3,normal4,normal5,highlighted5,highlighted6,normal7,normal8,normal9,normal10,normal11,normal12,highlighted11,highlighted12 and so on
Any help is always appreciated,
Thanks
If I understand, use a counter when after 5 and 6 insert in your list, add in normal list instead of highlighted list
Try this:
int highAdded = 0;
int normalAdded = 0;
for (Iterator<BaseItem> iterator = MyItems.iterator(); iterator.hasNext();) {
BaseItem itemtype = iterator.next();
if (itemtype.isHighlight()) {
highAdded++;
if (highAdded == 5) {
normal.add(itemtype);
} else if (highAdded == 6) {
normal.add(itemtype);
highAdded = 0;
} else {
highlighted.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
highlighted.add(itemtype);
} else if (normalAdded == 7) {
highlighted.add(itemtype);
normalAdded = 0;
} else {
normal.add(itemtype);
}
}
}
EDIT
I write this code:
public class StackOverFlowSample {
public static void main(String [] args) {
List<String> lst = new ArrayList<String>();
List<String> lstHigh = new ArrayList<String>();
List<String> lstNormal = new ArrayList<String>();
lst.add("highlighted01");
lst.add("highlighted02");
lst.add("highlighted03");
lst.add("highlighted04");
lst.add("highlighted05");
lst.add("highlighted06");
lst.add("highlighted07");
lst.add("highlighted08");
lst.add("highlighted09");
lst.add("highlighted10");
lst.add("highlighted11");
lst.add("highlighted12");
lst.add("highlighted13");
lst.add("highlighted14");
lst.add("highlighted15");
lst.add("highlighted16");
lst.add("normal01");
lst.add("normal02");
lst.add("normal03");
lst.add("normal04");
lst.add("normal05");
lst.add("normal06");
lst.add("normal07");
lst.add("normal08");
lst.add("normal09");
lst.add("normal10");
lst.add("normal11");
lst.add("normal12");
lst.add("normal13");
lst.add("normal14");
lst.add("normal15");
lst.add("normal16");
int highAdded = 0;
int normalAdded = 0;
for (Iterator<String> iterator = lst.iterator(); iterator.hasNext();) {
String itemtype = iterator.next();
if (itemtype.startsWith("highlighted")) {
highAdded++;
if (highAdded == 5) {
lstNormal.add(itemtype);
} else if (highAdded == 6) {
lstNormal.add(itemtype);
highAdded = 0;
} else {
lstHigh.add(itemtype);
}
}
else{
normalAdded++;
if (normalAdded == 6) {
lstHigh.add(itemtype);
} else if (normalAdded == 7) {
lstHigh.add(itemtype);
normalAdded = 0;
} else {
lstNormal.add(itemtype);
}
}
}
String result = "HIGHLIGHTED ARRAY: ";
for (String curr : lstHigh) {
result += curr + ", ";
}
System.out.print(result);
result = "NORMAL ARRAY: ";
for (String curr : lstNormal) {
result += curr + ", ";
}
System.out.print(result);
}
}
The output is:
HIGHLIGHTED ARRAY: highlighted01, highlighted02, highlighted03, highlighted04, highlighted07, highlighted08, highlighted09, highlighted10, highlighted13, highlighted14, highlighted15, highlighted16, normal06, normal07, normal13, normal14,
NORMAL ARRAY: highlighted05, highlighted06, highlighted11, highlighted12, normal01, normal02, normal03, normal04, normal05, normal08, normal09, normal10, normal11, normal12, normal15, normal16,
Tell me if it's OK ;)

Unexpected output in java when using ArrayList<ArrayList<String>>()

I have the following code in java, which takes in input from the user. It is basically a simple database system.
ArrayList<String> commands = new ArrayList<String>();
ArrayList<ArrayList<String>> blocks = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter the transaction commands.\n");
Scanner scan = new Scanner(System.in);
while(!(line = scan.nextLine()).toLowerCase().equals("end"))
{
commands.add(line);
}
for(String com : commands)
{
String split[] = com.split(" ");
if(!split[0].toLowerCase().equals("get") && !split[0].toLowerCase().equals("numequalto") && !split[0].toLowerCase().equals("rollback") && !split[0].toLowerCase().equals("commit"))
{
if(split[0].toLowerCase().equals("begin"))
{
if(!list.isEmpty())
{
blocks.add(list);
System.out.println(blocks.get(0));
list.clear();
}
else
{
continue;
}
}
else
{
list.add(com);
continue;
}
}
}
System.out.println(blocks.get(0));
The input I give for this program is:
set a 10
set b 20
begin
get a
get b
end
While the expected output is:
[set a 10, set b 20]
[set a 10, set b 20]
I get the output as:
[set a 10, set b 20]
[]
The problem seems to be that the value of the ArrayList> blocks, seems to be overwritten. The last print statement prints the value as an empty ArrayList. I cannot find the exact source of error. Any help in finding out the error will be greatly appreciated.
I believe the following code is the culprit:
blocks.add(list);
System.out.println(blocks.get(0));
list.clear();
You add the list to blocks. Note, when you are adding your list object to blocks, you are not copying the list.
So when you clear the list, it clears the list object that is also referenced in the blocks list.
To avoid this you could just:
blocks.add(list);
System.out.println(blocks.get(0));
list = new ArrayList<String>();
This will create a new list object and leave the one in your blocks list untouched.
Your second output is got from last line of System.out.println(blocks.get(0));. Have a look at your code, you add blocks.add(list); after a while you clear the list. As List is mutable, so blocks List is empty. So, your second output print nothing.
blocks.add(list); //list has added here with values
System.out.println(blocks.get(0));
list.clear(); // list here without values.
This giving correct answer as you expected.
remove that list.clear() statement
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> commands = new ArrayList<String>();
ArrayList<ArrayList<String>> blocks = new ArrayList<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
System.out.println("Enter the transaction commands.\n");
String line;
Scanner scan = new Scanner(System.in);
while (!(line = scan.nextLine()).toLowerCase().equals("end")) {
commands.add(line);
}
for (String com : commands) {
String split[] = com.split(" ");
if (!split[0].toLowerCase().equals("get")
&& !split[0].toLowerCase().equals("numequalto")
&& !split[0].toLowerCase().equals("rollback")
&& !split[0].toLowerCase().equals("commit")) {
if (split[0].toLowerCase().equals("begin")) {
if (!list.isEmpty()) {
blocks.add(list);
System.out.println("list :" + blocks.get(0));
// list.clear();
} else {
continue;
}
} else {
list.add(com);
continue;
}
}
}
System.out.println("output :" + blocks.get(0));
}
}
Answer i got is
list :[set a 10, set b 20]
output :[set a 10, set b 20]

How do i compare a variable's data with the data in an ArrayList?

I am calling a method that passes in a variable. I want to be able to compare this variable to all the items in an ArrayList to see if there is a match.
This is my code...
private boolean input;
private ArrayList chcekItem = new ArrayList();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
}
else {
Iterator iterators = getChcekItem().iterator();
while (iterators.hasNext()) {
if (iterators.next()==action) {
System.out.println(iterators.next()+"="+action);
input=false;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}
else{
System.out.println("The item " + action + " is Exist");
}
}
}
My code isn't working as I had expected. Could someone please help me fix the problem.
I take it that the checkItem variable is a List of Strings, thus it should be defined like this:
private List<String> checkItem = new ArrayList<String>();
When comparing an String you don't use string1==string2 but string1.equals(string2);
So
(iterators.next()==action)
should be:
(iterators.next().equals(action))
Remember to check the string for null values.
So the whole code could look like this:
private boolean input;
private List<String> chcekItem= new ArrayList<String>();
public void setAction(String action) {
input=true;
if (getChcekItem().isEmpty()) {
getChcekItem().add(action);
} else {
//Foreach loop instead of an iterator ;)
for(String item : chcekItem) {
if(item.equals(action)) {
System.out.println(item+"="+action);
input=false;
//We can jump out of the loop here since we already found a matching value
break;
}
}
if (input) {
getChcekItem().add(action);
System.out.println("The item " + action + " is Successfully Added to array");
}else{
System.out.println("The item " + action + " is Exist");
}
}
}
}

Calling Two Different Methods into One Method in Java

I wish to:
Reading in two files
Split the files into individual strings
Compare the two string lists and retrieve strings that are unique to a file.
At the moment I am running in to the problem of finding a way to call the two methods used to call in the files (one for each file) to the same method in order to be compared.
Both methods use a try-catch-while statement and if I try to read all of the entries after the while statement only a single is shown and not the entire list.
Is there a way to send parts of both methods as parameter to a single new method?
Here is the code for the program. I know that there are problems with the way that I am doing the program, but I am only doing it the way that I was taught.
File mainEmails = new File("Testrun.txt");
Scanner inputScanner = null;
int counter = 1;
String fullName = null;
String position = null;
String companyName = null;
String telNumber = null;
String emailAddress = null;
try
{
inputScanner = new Scanner(mainEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner.hasNextLine())
{
String nextLine = inputScanner.nextLine();
String [] splitFile = nextLine.split(",");
for (int i = 0; i <splitFile.length;i++)
{
if(i==0)
{
fullName = splitFile[0];
}
else if(i==1)
{
position = splitFile[1];
}
else if(i==2)
{
companyName = splitFile[2];
}
else if(i==3)
{
telNumber = splitFile[3];
}
else if(i==4)
{
emailAddress = splitFile[4];
}
else if(splitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
public static void deletionList()
{
File deletionEmails = new File("Testrun1.txt");
Scanner inputScanner1 = null;
String deletionfullName = null;
String deletionposition = null;
String deletioncompanyName= null;
String deletiontelNumber = null;
String deletionemailAddress = null;
try
{
inputScanner1 = new Scanner(deletionEmails);
}
catch(FileNotFoundException e)
{
System.out.println("File has not been found.");
}
while (inputScanner1.hasNextLine())
{
String deletionnextLine = inputScanner1.nextLine();
String [] deletionsplitFile = deletionnextLine.split(",");
for (int i = 0; i <deletionsplitFile.length;i++)
{
if(i==0)
{
deletionfullName = deletionsplitFile[0];
}
else if(i==1)
{
deletionposition = deletionsplitFile[1];
}
else if(i==2)
{
deletioncompanyName = deletionsplitFile[2];
}
else if(i==3)
{
deletiontelNumber = deletionsplitFile[3];
}
else if(i==4)
{
deletionemailAddress = deletionsplitFile[4];
}
else if(deletionsplitFile[i] == null)
{
System.out.println("You have failed!");
}
}
}
}
What I am trying to do is to take the fullName, emailAddress from the first split and deletionfullName and deletionemailAddress from the second split and compare the first and second of each, respectively. Each file will have a number of fields in it, and I am only interested in the fullName and emailAddress fields.
It is quite confusing to understand how you are trying to implement your solution, so may I suggest you look at a different way of doing the whole read-and-compare process. For example, I would suggest doing something like this... (in psuedocode)
public void compareFiles(String file1, String file2){
// Read the lines of each file into String[] arrays
String[] file1Lines = readAndSplitIntoLines(file1);
String[] file2Lines = readAndSplitIntoLines(file2);
// compare the lines
for (int x=0;x<file1Lines.length;x++){
for (int y=0;y<file2Lines.length;y++){
if (file1Lines[x].equals(file2Lines[y])){
// match. set it to null
file1Lines[x] = null;
file2Lines[y] = null;
// break out of the inner loop and start comparing the next line
break;
}
}
// remove the duplicates (which are now null values), creating a smaller array of uniques.
String[] newFile1 = shrinkArrayByRemovingNulls(file1Lines);
String[] newFile2 = shrinkArrayByRemovingNulls(file2Lines);
}
Besides the fact that your question is not very clear, you have at least one glaring problem:
DO NOT use exception handling for logic! Exception handling should be only for exceptions.
Secondly, think about what you are really looking to do. In pseudocode it would look something like this:
list1 = split(file(name1).read())
list2 = split(file(name2).read())
list3 = unique(list1, list2)
What does your code look like?

Categories

Resources