-4

i need some help with a java code,

This is my code:

public void showData() {

        int pass = 0;

        /* For first list */
        for(int i = 0; i < first_list.length; i++) {

            if(first_list[pass].toString() != second_list[i].toString()) {
                System.out.println(first_list[i]);

            } else {

            }

        }

        pass++;
    }

The output:

  • Porto
  • Algarve

But i dont want this and i understand that by doing this way, my for ends and dont do other passes.. i want to get all possible combinations without repeat words, the output that i want is this one:

  • Porto
  • Algarve
  • Lisboa
  • Algarve
  • Lisboa
  • Porto

This is a draw to help understand: enter image description here

How can i do such thing? Thank you!

EDIT: Im not asking how to compare strings... if someone can point me a topic with what i want, it would be nice, if not.. well some advices would be great

user3000019
  • 103
  • 1
  • 10
  • njzk that topic, dont helps me doing what i want, im not asking how to compare strings... – user3000019 Jan 28 '16 at 20:23
  • You need all permutations, right? Think how you logically would do it, step by step on a piece of paper. You would combine the first element with the second. Then with the third. Now, what do you do with the next element in the next iteration? Then translate that to code. You're on the right track, but you're over complicating it. – NilsH Jan 28 '16 at 20:29
  • @user3000019, that may not be what you're asking, but it will help you. – shmosel Jan 28 '16 at 20:30
  • @user3000019 whatever it is you are trying to do, the first issue is that string comparison. – njzk2 Jan 28 '16 at 20:56

2 Answers2

1

The question is not entirely clear, but if If I've understood you correctly, you'll want something like this:

String[] locations = {"Lisboa", "Porto", "Algarve"};

for (String source : locations) {
    for (String destination : locations) {
        if (!source.equals(destination)) {
            System.out.println(source + " -> " + destination);
        }
    }
}
shmosel
  • 49,289
  • 6
  • 73
  • 138
0

Use a set?

Set<String> mySet = new HashSet<String>();
for(String s:first_list)
  mySet.add(s);

for(String s:second_list)
  mySet.add(s);

for(String s:mySet)
  System.out.println(s);
Abhishek Anand
  • 1,940
  • 14
  • 27
  • Why exactly, it has been marked negative? The thread opener, wants single set of names from two arrays, without having any duplicates. – Abhishek Anand Jan 28 '16 at 20:43
  • Thanks for your help, in my case, the shmosel solution its the best, but thanks for your time! and i dont understand why it has been marked negative.. – user3000019 Jan 28 '16 at 20:46