import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; public class Main { public static void printHead(ArrayList list,int n) { for(int idx = 0 ; idx list,int n) { for(int idx...

1 answer below »
Create a java program. Please include output photos.


import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; public class Main { public static void printHead(ArrayList list,int n) { for(int idx = 0 ; idx < n="" ;="" idx++)="" {="" system.out.println(list.get(idx).tostring());="" }="" }="" public="" static="" void="" printhead(tweet[]="" list,int="" n)="" {="" for(int="" idx="0" ;="" idx="">< n="" ;="" idx++)="" {="" system.out.println(list[idx].tostring());="" }="" }="" public="" static="" void=""> list,int n) { for(int idx = list.size() ; idx > list.size() - n ; idx--) { System.out.println(list.get(idx-1).toString()); } } public static void prinTail(Tweet[] list,int n) { list = Arrays.stream(list).filter(Objects::nonNull).toArray(Tweet[]::new); // since we created array dynamically , end of array we have have some null values so removed those for(int idx = list.length ; idx > list.length - n ; idx--) { System.out.println(list[idx-1].toString()); } } public static void main(String[] args) { String fileName = "tweets_data.csv"; int tweetCnt = 5; // used to print first and last n tweets from tweets array and array lists ArrayList tweetList = TweetLoader.loadAsArrayList(fileName); Tweet[] tweetArr = TweetLoader.loadAsArray(fileName); System.out.println("First "+tweetCnt +" tweets using array"); System.out.println("================================================"); printHead(tweetArr,tweetCnt); System.out.println(); System.out.println("First "+tweetCnt +" tweets using array list"); System.out.println("================================================"); printHead(tweetList,tweetCnt); System.out.println(); System.out.println("Last "+tweetCnt +" tweets using array list"); System.out.println("================================================"); prinTail(tweetList,tweetCnt); System.out.println(); System.out.println("Last "+tweetCnt +" tweets using array"); System.out.println("================================================"); prinTail(tweetArr,tweetCnt); } } public class Tweet { private int uniqueId; private String segmentCategory; private String text; public int getUniqueId() { return uniqueId; } public void setUniqueId(int uniqueId) { this.uniqueId = uniqueId; } public String getSegmentCategory() { return segmentCategory; } public void setSegmentCategory(String segmentCategory) { this.segmentCategory = segmentCategory; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Tweet(int uniqueId, String segmentCategory, String text) { this.uniqueId = uniqueId; this.segmentCategory = segmentCategory; this.text = text; } public String toString() { return this.uniqueId +" ("+this.segmentCategory+") : "+this.text; } } import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; public class TweetLoader { public static ArrayList loadAsArrayList(String fileName) { ArrayList tweetsData = new ArrayList<>(); BufferedReader csvReader = null; try { csvReader = new BufferedReader(new FileReader("src/" + fileName)); String row = null; Tweet tweet = null; while ((row = csvReader.readLine()) != null && !"".equals(row)) { String tempStr[] = row.split("\\,"); tweet = new Tweet(Integer.parseInt(tempStr[1].trim()), tempStr[0].trim(), tempStr[2].trim()); tweetsData.add(tweet); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { csvReader.close(); } catch (IOException e) { e.printStackTrace(); } } return tweetsData; } public static Tweet[] loadAsArray(String fileName) { int arraySize = 10; Tweet[] tweetsData = new Tweet[arraySize]; BufferedReader csvReader = null; int indexPos = 0; try { csvReader = new BufferedReader(new FileReader("src/" + fileName)); String row = null; Tweet tweet = null; while ((row = csvReader.readLine()) != null && !"".equals(row)) { if (tweetsData.length == indexPos) { tweetsData = Arrays.copyOf(tweetsData,tweetsData.length*2); // doubling the array size } String tempStr[] = row.split("\\,"); tweet = new Tweet(Integer.parseInt(tempStr[1].trim()), tempStr[0].trim(), tempStr[2].trim()); tweetsData[indexPos] = tweet; indexPos++; } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { csvReader.close(); } catch (IOException e) { e.printStackTrace(); } } return tweetsData; } }
Answered Same DayFeb 15, 2021

Answer To: import java.util.ArrayList; import java.util.Arrays; import java.util.Objects; public class Main {...

Valupadasu answered on Feb 16 2021
154 Votes
console output.png
Main.java
Main.java
import java.util.Arrays;
import java.util.Objects;
public class Main {
    public static void printResults(Object[] arr) {
            System.out.println(arr[0] == null ? "Not found" : arr[0].toString());
    }
    public static void main(String[] args) {
        String fileName = "tweet_data_sorted.csv";
        Tweet[] tweetArr = TweetLoader.loadAsArray(fileName);
        tweetArr = Arrays.stream(tweetArr).filter(Objects::nonNull).toArray(Tweet[]::new); // since we created array dynamically , end of array we have have some null values so removed those
        int tweetIdForSearch[] = { 1000, 1005, 1804, 2499, 2504, 2800 };
        for (int id : tweetIdForSearch) {
            System.out.println("================================");
            System.out.println("Finding tweet with Id " + id);
            System.out.println("Using linear search");
            printResults(SearchObject.linearSearch(tweetArr, tweetArr.length, new Tweet(id, "", "")));
            System.out.println("Using binary search");
            Arrays.sort(tweetArr); // array to be sorted for binary search
            printResults(SearchObject.binarySearch(tweetArr, tweetArr.length, new Tweet(id, "", "")));
        }
    }
}
SearchObject.java
SearchObject.java
public class SearchObject {

    public static Object[] linearSearch(Object[] inputArray, int arraySize, Object searchKey) {
        Object[] output = new Object[1];
        for(int idx=0; idx < arraySize ; idx++){ 
            if(inputArray[idx].equals(searchKey)){ 
                output[0] =  inputArray[idx];
                return output;
            } 
        } 
        return output; 
    }

    public static int binarySearch(Object[
] inputArray, Comparable searchKey, int first, int last){
        if(first > last)
            return -1; 
        else{
            int mid = (first + last) / 2; 
            int compResult = searchKey.compareTo(inputArray[mid]);
            if(compResult == 0)
                return mid; 
            else if (compResult < 0)
                return binarySearch(inputArray, searchKey, first, mid -1);
            else
                return binarySearch(inputArray, searchKey, mid + 1, last);
        }
    }

    public static Object[] binarySearch(Object[] inputArray, int arraySize, Comparable searchKey) {
        Object[] output = new Object[1];
        int index = binarySearch(inputArray, searchKey, 0, arraySize -1); 
        if(index >= 0)
            output[0] = inputArray[index];
        return output;
    }
}
Tweet.java
Tweet.java
public class Tweet implements Comparable {
    private int uniqueId;
    private String segmentCategory;
    private String text;
    public int getUniqueId() {
        return uniqueId;
    }
    public void setUniqueId(int uniqueId) {
        this.uniqueId = uniqueId;
    }
    public String getSegmentCategory() {
        return segmentCategory;
    }
    public void setSegmentCategory(String segmentCategory) {
        this.segmentCategory = segmentCategory;
    }
    public String getText() {
        return text;
    }
    public void setText(String text) {
        this.text = text;
    }
    public Tweet(int uniqueId, String segmentCategory, String text) {
        this.uniqueId = uniqueId;
        this.segmentCategory = segmentCategory;
        this.text = text;
    }
    public String toString() {
        return this.uniqueId + " (" + this.segmentCategory + ") : " + this.text;
    }

    public boolean equals(Object o) {
        return this.uniqueId == ((Tweet) o).getUniqueId();
    }
    @Override
    public int compareTo(Object o) {
        if (this.uniqueId < ((Tweet) o).getUniqueId())
            return -1;
        else if (this.uniqueId > ((Tweet) o).getUniqueId())
            return 1;
        else
            return 0;
    }
}
tweet_data_sorted.csv
Pos,1459,@Blackberry & @Facebook U R really about to make me throw this @Blackberry in the trash an get an @Apple iPhone! @Facebook upload issues!
Pos,1000,Now all @Apple has to do is get swype on the iphone and it will be crack. Iphone that is
Pos,1005,@Apple will be adding more carrier support to the iPhone 4S (just announced)
Pos,1008,Hilarious @youtube video - guy does a duet with @apple 's Siri. Pretty much sums up the love affair! http://t.co/8ExbnQjY
Pos,1012,@RIM you made it too easy for me to switch to @Apple iPhone. See ya!
Pos,1015,I just realized that the reason I got into twitter was ios5 thanks @apple
Pos,1018,I'm a current @Blackberry user little bit disappointed with it! Should I move to @Android or @Apple @iphone
Pos,1021,The 16 strangest things Siri has said so far. I am SOOO glad that @Apple gave Siri a sense of humor! http://t.co/TWAeUDBp via @HappyPlace
Pos,1026,Great up close & personal event @Apple tonight in Regent St store!
Pos,1028,From which companies do you experience the best customer service aside from @zappos and @apple?
Pos,1033,Just apply for a job at @Apple hope they call me lol
Pos,1036,RT @JamaicanIdler: Lmao I think @apple is onto something magical! I am DYING!!! haha. Siri suggested where to find whores and where to h ...
Pos,1039,Lmao I think @apple is onto something magical! I am DYING!!! haha. Siri suggested where to find whores and where to hide a body lolol
Pos,1042,RT @PhillipRowntree: Just registered as an @apple developer... Here's hoping I can actually do it... Any help greatly appreciated!
Pos,1045,Wow. Great deals on refurbed #iPad (first gen) models. RT: Apple offers great deals on refurbished 1st-gen iPads http://t.co/ukWOKBGd @Apple
Pos,1047,Just registered as an @apple developer... Here's hoping I can actually do it... Any help greatly appreciated!
Pos,1052, ! Currently learning Mandarin for my upcoming trip to Hong Kong. I gotta hand it to @Apple iPhones & their uber useful flashcard apps
Pos,1056,Come to the dark side @gretcheneclark: Hey @apple if you send me a free iPhone I will publicly and ceremoniously burn my #BlackBerry.
Pos,1058,Hey @apple if you send me a free iPhone (any version will do) I will publicly and ceremoniously burn my #BlackBerry.
Pos,1063,Thank you @apple for Find My Mac - just located and wiped my stolen Air. #smallvictory #thievingbastards
Pos,1066,Thanks to @Apple Covent Garden #GeniusBar for replacing my MacBook keyboard/cracked wristpad during my lunch break today out of warranty.
Pos,1068,@DailyDealChat @apple Thanks!!
Pos,1073,iPads Replace Bound Playbooks on Some N.F.L. Teams http://t.co/2UXAWKwf @apple @nytimes
Pos,1077,@apple..good ipad
Pos,1082,@apple @siri is efffing amazing!!
Pos,1087,Amazing new @Apple iOs 5 feature. http://t.co/jatFVfpM
Pos,1092,RT @TripLingo: We're one of a few Featured Education Apps on the @Apple **Website** today sweet! http://t.co/0yWvbe1Z
Pos,1095,We're one of a few Featured Education Apps on the @Apple **Website** today sweet! http://t.co/0yWvbe1Z
Pos,1099,When you want something done right you do it yourself... or go to @Apple. AT&T you're useless these days. #yourdaysarenumbered
Pos,1101,We did an unexpected workshop for the #iPhone4S at @apple yesterday and we got an awesome amount of info #notjustaboutthephone @gamerchik16
Pos,1105,<3 #ios5 @apple
Pos,1107,--- RT @Apple No question bro. RT @AintEeenTrippin: Should I get dis iPhone or a EVO 3D?
Pos,1111,RT @imightbewrong: I'm OVER people bitching about the #iPhone4S... I think it's the smartest phone I've ever had and I'm very happy. : ...
Pos,1114,I'm OVER people bitching about the #iPhone4S... I think it's the smartest phone I've ever had and I'm very happy. :) Way to go @Apple!
Pos,1117,@Twitter CEO points to @Apple as 'corporate mentor' as @iOS signups triple http://t.co/GCY8iphN
Pos,1122,At the bus with my iPhone ;) thxx @apple
Pos,1127,@azee1v1 @apple @umber AppStore is well done so is iTunes on the mobile devices. I was talking about desktop app.
Pos,1128,NYTimes: Coach Wants to See You. And Bring Your iPad. http://t.co/J2FTiEnG #iPad @apple set red 42 red 42 hut hut @NFL wish I had an #iPad
Pos,1129,@apple @jilive @DanielPink: Apple sells 4 million iPhone 4S units in first weekend ... Steve Jobs brilliance lives on for ever! #iphone #RVA
Pos,1130,@bkad5161 than apologize to @apple ;)
Pos,1134,@Apple downloads of iOS 5 are proving popular with users -- http://t.co/NSHLfiUX
Pos,1137,Lmfao look at the argument I had with Siri !!@ijustine @apple http://t.co/D4VjL7SI
Pos,1141,Incredible: 4 million iPhone 4Ss in 3 days. 135% better than the iPhone 4 http://t.co/1FMJxTMM @apple #iphone4s
Pos,1145,Save me from #HP's unwanted OS! Help me buy an #iPhone! I have seen the light! #lol http://t.co/8gUP9Acz #backchannel @apple
Pos,1146,Well @apple fixed my #ios5 battery drain problem with a replacement iPhone 4 -- it's working like a champ now
Pos,1151,Currently ordering a BRAND NEW MACBOOK PRO!!! Bahhh... my MacBook is 5 years old. I'll miss it. But it's time. cc: @Apple -
Pos,1152,you are so blessed. @apple
Pos,1154,#Siri now knows who my dad mom brother and girlfriend is. Thanks @apple
Pos,1156,Well at least the @apple store has amazing call waiting music! #need4s
Pos,1157,#sweet... #apple replaced my glass #probono. thank you @apple
Pos,1161,Not Bad! @Apple Sells Over 4 Million #IPhones in Debut Weekend - Bloomberg http://t.co/AVSl3ygU - #smartphone #sm RT @VinodRad
Pos,1166,loving new technology from @apple iPhone 4s mac air and iCloud are unreal #technology
Pos,1170,I'm loving this new IOS5 update :) @apple
Pos,1173,Another mention for Apple Store: http://t.co/fiIOApKt - RT @floridamike Once again getting great customer service from the @apple store ...
Pos,1174,Time to go get my iPhone 4s. Looking forward to sticking it to the man by no longer paying for most texts. Thanks @apple.
Pos,1177,hey @apple I hate my computer i need a #mack wanna send me a free one.
Pos,1182,Thank you @apple. My new gf(iphone4s) is great! She does everything!
Pos,1185,#iCloud set up was flawless and works like a champ! To the Cloud @Apple
Pos,1187,@Wisconsin_Mommy @Apple I'd totally email the company... I always get great service at our @Apple store!
Pos,1188,@apple loving the new IOS5 upgrade for the iPhone!
Pos,1189,The nice @apple tech support guy fixed my iTouch =D
Pos,1190,Once again getting great customer service from the @apple store at millenia mall.
Pos,1195,Is it just me or is #iOS5 faster for the iPad? @apple
Pos,1199,I love our @apple imac even though I haven't seen my hubby in 3 days now! #geek
Pos,1204,making the switch from @Android to @Apple #iphone #iphone4S #smartphone #stevejobs (@ Apple Store) http://t.co/kj6pJvkH
Pos,1208,So THANKFUL for the incredible people @apple for going above and beyond and offering to and replacing my water-damaged Macbook Pro!!! Wow!
Pos,1210,Play on ma man. Loving the camera in the #iphone4s. Well done @apple #fb http://t.co/tmdFqRe1
Pos,1215,So yeah... @apple #iOS5 #readinglists have changed my life. #nowicanspendevenmoretimeonmyphone.
Pos,1220,@Apple Safari Reader owns the worldwide web
Pos,1223,I love @apple service . My case has cracked 3x and I go in and they hand me a case and I walk out
Pos,1227,#10twitterpeopleiwouldliketomeet @coollike @TheGadgetShow @thelittleappkid @Jon4Lakers @BenRubery @Apple @twitter @FXhomeHitFilm (-2)
Pos,1230,Said to have laid out the next 4 years @apple.Jobs last iPhone is 2012 not the iPhone4S. iPhone(4G/5) 2012 is magical! http://t.co/DxxklUBp
Pos,1234,Kind of excited. On my way to my last class right now and then going to the @Apple store so buy #MacOSC Snow Leopard and Lion :-)
Pos,1238,i used to be with @blackberry over 4-5yrs .. after all the disruptions and lost gigs thx to their service im moving to @apple #iphone
Pos,1240,Apple sells 4 million iPhones in 3 days @apple keep doing what you are doing because you are doing it well! http://t.co/ZZc6bE0w
Pos,1241,Yessss! I'm lovin the iPhone update especially the slide down bar at top of screen =) good job @Apple.
Pos,1244,4 millions in a weekend 16 #iPhone4S per second. This is madness?! no this is @Apple !!!
Pos,1245,.@apple you got me. I'm now invested. MacBook Pro next year. Time to get on selling more of my #android gear
Pos,1248,@iancollinsuk @apple I like what you did there...!
Pos,1251,I just sent my grandma a post card using my #CardsApp thanks @Apple
Pos,1252,Sorry @BlackBerry I'm moving to @Apple.
Pos,1257,@KostaTsetsekas @apple Putting it in the wash is kind of the equivalent to Will it blend? Glad to hear it's still alive.
Pos,1259,Laundering Ari's iPhone not my finest moment. But after drying in bag of (organic :-) rice for 4 days it booted up!!!!!!!!!!! @apple
Pos,1261,Bravo @Apple! http://t.co/BgoTzj7K
Pos,1265,God Bless @YouTube @apple for #appletv & our bad ass system. LOVING #PrincessOfChina. GB to @coldplay & @rihanna too :)
Pos,1270,Been off twitter for a few days as I smashed my iPhone but @apple were very nice and gave me a new one :)
Pos,1271,Thank you @Apple iOS 5 for email pop up on the lock screen and opening it when unlocking.
Pos,1276,One word - #wow. RT @jldavid iPhone 4S First Weekend Sales Top Four Million: http://t.co/Zx5Pw0GT (via @apple)
Pos,1281,This good here iPhone will do me VERY well today. Thanks to the gods that are @apple.
Pos,1283,RT @MN2NOVA: Love ios5 Easter eggs. Pull down from middle top to bottom and see what pulls down. Awesome little feature! #ios5 @apple
Pos,1286,Love ios5 Easter eggs. Pull down from middle top to bottom and see what pulls down. Awesome little feature! #ios5 @apple
Pos,1291,Love #ios5 Easter eggs. Pull down from middle top to bottom and see what pulls down. Awesome little feature! @apple #lovemyiphone
Pos,1292,Updated my iOS and started using cloud services. Pretty bad ass @apple my #iPhone 3GS still the champ.
Pos,1294,Gone for a run beautiful morning man do I love iOS 5 @apple #iPhone
Pos,1295,@apple your simply the best.
Pos,1300,I must admit @apple has made me a very happy camper! I have text tones now! Lol! Ring tone: #MakeMeProud Drakes vers! Text tone: Nicki's
Pos,1301,Day305 I'm thankful for the great customer service received today from @Apple via phone CS new phone on the way #365daysofgratefulness
Pos,1304,S/O to @apple for replacing my phone for free
Pos,1306,Loving the new iPod update @apple
Pos,1309,@alexlindsay My wife upgraded her iPhone 4. I think Siri alone is worth the upgrade. Looking forward to @Apple continuing to enhance Siri.
Pos,1313,RT @tomkeene Thx @instagram Thx @apple #hypo #D-76 #tri-x http://t.co/BPPJwncp
Pos,1318,@SteveJobs being honored tonite @Apple...A truly great loss to the world.He will so be missed
Pos,1319,Thx @instagram Thx @apple #hypo #D-76 #tri-x http://t.co/D7EeJHBT
Pos,1320,Loving my new #iPhone4S thanks @apple for #ios5
Pos,1324,i love this. so much. thank you @apple. http://t.co/Ui8lOEzX
Pos,1327,@apple the iPhone 4s is great #genius
Pos,1331,@apple Cards app notifies me the card I sent has arrived at local post office and should be delivered today... Sunday. Truly is #magic.
Pos,1336,Love my new I0S5 @Apple updates. Just when I think it can't get any better somehow it simplifies my life more. That's right-it's an Apple.
Pos,1338,@apple Siri is amazing
Pos,1340,@rygurl you need an @apple iphone4S with Siri!
Pos,1342,Meet #Siri your new iPhone butler. Click the link and be amazed by all it can do: http://t.co/lvfFdCEL @Apple
Pos,1344,So I am using my work PC (NEVER EVER) to get a feel for it; it has the worst speakers ever!! @apple you have spoiled me!! #imamac
Pos,1347,I @Apple http://t.co/a8on3IAa
Pos,1349,@apple just got the new iOS5 upgrade with iMessage...good luck surviving now @BlackBerry
Pos,1351,Loving #iOS5 !! #awesome @Apple
Pos,1356,RT @MattyRiesz: @kathrynyee You were right an iPhone is a must have. #addicted {WELCOME TO THE @APPLE CLUB}
Pos,1361,Thank you @apple for your innovations. Exhibit A: Guy playing with Facetime instead of watching game at sports bar. http://t.co/oU7K39ge
Pos,1364,@blackberry boo hiss!............@apple wuhu!!!!!!!! When will my berry powered technology actually work??
Pos,1365,@apple by far the best iPod and first time iPhone ever.... Good job guys
Pos,1370,Thank you Steve @apple store 5th av. http://t.co/nSAisriP
Pos,1374,@Apple's Siri is witchcraft. What's next @googleresearch. 2 yr lead lost?
Pos,1376,@Apple iOS 5 is sweet! Notifications phone search covers mail now wifi sync iCloud backup and integrated Twitter are all well done.
Pos,1378,RT @katebetts: Another great James Stewart story in today's NY Times about importance of architecture in @apple retail success http://t. ...
Pos,1383,Another great James Stewart story in today's NY Times about importance of architecture in @apple retail success http://t.co/Kniz452s
Pos,1386,I <3 @apple http://t.co/ondXWpEr
Pos,1390,Welcome to the twitter world @MarkStuver. This is due to #iOS5 and @apple thanks guys.
Pos,1394,Impressive service @apple genius bar metro centre. Power cable replaced free n booked in for screen replacement for free :- D
Pos,1395,RT @deb_lavoy: the nice guy at the @apple store replaced my phone gratis when I showed him the hairline crack on the screen. thanks @apple
Pos,1399,the nice guy at the @apple store replaced my phone gratis when I showed him the hairline crack on the screen. thanks @apple
Pos,1400,My iPhone 4S battery lasted longer than a day. That hasn't happened since my edge iPhone. Nice job @apple.
Pos,1404,It would have taken me 15 mins to write this with my #Blackberry. Thank u @Apple 4s for converting me and showing me the grass is greener!
Pos,1407,RT @herahussain: @RickySinghPT got a new backside for my eye phone! V impressed with @apple
Pos,1412,@RickySinghPT got a new backside for my eye phone! V...
SOLUTION.PDF

Answer To This Question Is Available To Download

Related Questions & Answers

More Questions »

Submit New Assignment

Copy and Paste Your Assignment Here