Ankush Singh
Ankush Singh

Reputation: 560

HashSet Output not matching [JAVA]

The code is to read from file and the generate a HashSet and then output to the console.

My code output and the expected output is not matching.

My java code is

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedReader brf = new BufferedReader(new FileReader("calllog.txt"));


        Set<String> phoneNumberList = new HashSet<String>();


        String read = "";
        while ((read = brf.readLine()) != null) {

            String[] callList = read.split(",");


            String in = callList[0];
            phoneNumberList.add(in);     //add(new CallLog(callList[0], startTime, endTime));


        }
        brf.close();

        Iterator<String> itr = phoneNumberList.iterator();

        while(itr.hasNext()){
            System.out.println(itr.next());
        }


    }

}

calllog.txt

8123456789,10-10-2015 10:00:00,10-10-2015 10:28:59
8123456789,11-10-2015 11:00:00,10-10-2015 11:51:00
8123456789,12-10-2015 12:00:00,10-10-2015 12:10:35
9123456789,11-10-2015 11:00:00,11-10-2015 11:32:43
0422-201430,12-10-2015 12:00:00,12-10-2015 11:05:16
0422-201430,12-10-2015 12:06:00,12-10-2015 11:10:20
9764318520,13-10-2015 13:00:00,13-10-2015 10:10:15
0422-201430,12-10-2015 12:00:00,12-10-2015 12:05:16
0422-201430,13-10-2015 14:05:00,13-10-2015 14:15:00
0422-201430,15-10-2015 16:08:00,15-10-2015 16:35:57

My output

9123456789
9764318520
0422-201430
8123456789

Expected output

8123456789
9764318520
0422-201430
9123456789

Upvotes: 2

Views: 115

Answers (1)

Eran
Eran

Reputation: 393771

HashSet is not ordered, so there is no reason for you to expect a certain ordering of the elements.

You could use a LinkedHashSet if you want your elements to be ordered according to insertion order, but that would give you

8123456789
9123456789
0422-201430
9764318520

which is not your expected order.

Upvotes: 4

Related Questions