java


Find unique element in an arraylist error


Im new to array list. I have a program where I want to find unique cities. I use for loop to use this but it doesn't seem to display what I want it to be. May I know where did I went wrong?
run:
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Malaysia
Enter size of city: Medium
Enter postal code: 132222
___________________________________________
List Of Unique Cities:
Malaysia,Singapore,Singapore,Singapore,Malaysia,Singapore,
I want it to print like this
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Singapore
Enter size of city: Small
Enter postal code: 132115
___________________________________________
Enter name of city: Malaysia
Enter size of city: Medium
Enter postal code: 132222
___________________________________________
List Of Unique Cities:
Malaysia,Singapore,
public class TravellingApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
SalesPerson s1 = new SalesPerson();
for(int j=1; j<=20; j++)
{
System.out.print("Enter name of city: ");
String name = sc.nextLine();
System.out.print("Enter size of city: ");
String size = sc.nextLine();
System.out.print("Enter postal code: ");
int postalCode = sc.nextInt();
sc.nextLine();
System.out.println("___________________________________________");
City c1 = new City(name, size, postalCode);
s1.addCity(c1);
}
System.out.println("List Of Unique Cities: ");
for (int i = 0; i < s1.returnListOfCities().size(); i++)
{
for (int k = s1.returnListOfCities().size() - 1; k >= i; k--)
{
if (s1.returnListOfCities().get(i).equals(s1.returnListOfCities().get(k)))
{
s1.returnListOfCities().remove(s1.returnListOfCities().get(i));
break;
}
System.out.print(s1.returnListOfCities().get(k) + ",");
}
}
}
}
Your City class must override the method equals() to get your desired behavior of equals() (the default just tests the object reference. This behavior is not what you want).
By the way, you don't even need to do this duplicate detection. Just switch to use the interface Set, and it can guarantee that all elements in the set is unique. If you don't care about order, then you can use the implementation HashSet as the implementation. So, implement City#hashCode() and then switch to use this line:
Set<City> s1 = new HashSet<>();
If you want to keep your original list untouched, and build a new one with the distinct values, here is how you can do using java8 streams :
List<City> allCities = s1.returnListOfCities();
List<City> distinctCities = allCities.stream().distinct().collect(Collectors.toList());
As already said and explained, your City must override equals().
Using stream, you can also pretty print your list like that :
System.out.println(allCities.stream().distinct().map(City::getName).collect(Collectors.joining(",")));
Or, if you cannot override City with equals() (let's say it's already defined to compare on postcode, but you want to compare on name), you can do :
System.out.println(allCities.stream().map(City::getName).distinct().collect(Collectors.joining(",")));
In that case, the names are directly compared as String's.

Related Links

how to avoid GC pauses?
Empty ListView doesn't appearance style
Realm Result returning null
How to use classes in android [closed]
int cant be converted into resultSet
Spring: Singleton that should be loaded initialized at startup
JDBC code optimization [duplicate]
Unable to locate persistence unit in web application
swipe tablayout is not working correctly
Android SecretFactory: Strongest/Most Recommended Hashing Algorithm
Switching activities with if statements and a random number generator
Android - Way to get a list of all resources that are used in given class
Record and play h.264 video in memory using Jcodec
Cannot use storm command line interface to kill topology
SQL query for SQLite / java.text.ParseException: Unparseable date
What is the correct order to close input streams?

Categories

HOME
compiler-construction
testing
yii2
clips
netsuite
magnific-popup
reflection
drivers
single-sign-on
session
syntax
tesseract
cplex
cmd
onelogin
constraint-programming
uber-api
quicklook
event-handling
circuit
fatal-error
facebook-page
footer
pythonanywhere
django-cms
shared-hosting
lucene.net
lldb
predix
sylius
restful-authentication
h2db
numerical-methods
socialengine
directx-10
titanium-mobile
openoffice.org
host
git-merge
streamsets
jna
webdriver-manager
preconditions
unoconv
eigenvalue
isbn
import-from-excel
cubic-spline
apache-fop
upstart
tizen-native-app
recursive-datastructures
brightcove
diagnostics
sqlbulkcopy
pillow
gcsfuse
django-scheduler
chord-diagram
yt-project
nxt
qpid
python-stackless
independentsoft
feedback
wyam
asp.net-dynamic-data
asp.net-web-api-odata
uitouch
contenttype
centos5
floating-point-precision
.aspxauth
ftps
dataadapter
sharp-repository
free-variable
coderush
funscript
frameset
wse3.0
osql
netbeans-6.9
subscript
fireworks
gnu-prolog
nsobject
ecl
multi-tier
nintendo-ds
exchange-server-2003

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App