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

Jackson parse array inside array
Java - is there a thread safe way to allocate new objects without locks?
Java deployment process
Developing and testing an OpenCV application on desktop which should later run on Android
how can I get layout like added image?
How do I pass an implemented Interface object to a method in the class its implemented in?
only the first client request arrives to the server when using java sockets
failed to connect to postgres server
Liferay - Call a controller of a remote portlet
Initilize constant on if java
How do I make my code convert Roman Numerals to numbers?
serial port how do I?
JDBC driver in WebApp or Tomcat
Unable to open file from Java file which is in current Directory using Netbeans
Declaring implicit field in XStream
Limiting the number of java core and heap dumps

Categories

HOME
ms-access
blogger
debugging
keycloak
zeromq
isabelle
fft
jira
graphql
wamp
convolution
upload
webrequest
python-unittest
user-input
wheelnav.js
dax
etl
gz
quickfix
uitypeeditor
graphlab
angular-ui
text-rendering
oxyplot
nas
captiveportal
maxmind
xacml
bpel
exuberant-ctags
airconsole
scorm2004
commit
atl
stacked
main
hockeyapp
serverside-rendering
sharefile
unspecified
webix-treetable
nand2tetris
spring-security-kerberos
nxlog
node-sass
eclipse-gef
logfiles
prolog-setof
kbuild
sqlbulkcopy
linode
mcafee
color-profile
root-framework
xcb
ableton-live
passport-google-oauth
pcf
sigabrt
superstack
hexdump
system.management
reactive-banana
qtableview
teamcity-8.0
comobject
fouc
coveralls
embedded-code
muse
riak-cs
ios9.1
apache-commons-fileupload
vstest.console.exe
dereference
javax.mail
csquery
knuth
typeof
didselectrowatindexpath
balanced-payments
oam
lcs
clipper
path-separator
nsnetservice
bluepill
postgresql-performance
code-cleanup
work-stealing
stage
sql-server-profiler
infrastructure
firefox4
brewmp
data-driven
mtj
port-number
spec#
genealogy
dbisam
wsdl.exe

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App