Moe Moe - 2 years ago 137
Java Question

How to combine elements from a List without duplicates using Java

I am trying to iterate and combine values from a list. My list is [A,B,C,D]. and I am looking for a way to output the following.

AB
AC
AD
BC
BD
CD


Here is my code:

List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
for (int i = 0; i<list.size()-1; i++){
for (int k = 0; k<list.size()-1; k++){
if (list.get(i)!=list.get(k+1)){
System.out.println(list.get(i)+list.get(k+1));
}
}
}


Code output

AB
AC
AD
BC
BD
CB //Note this value: I already have BC -- and I consider BC==CB
CD


I am not sure if scanner is an option here...
it gets more messy if I have more elements in the list. more items in the list means more duplicates such as xx, yy, xy yx.

Answer Source
List<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");
    list.add("C");
    list.add("D");
    for (int x = 0; x < list.size() - 1; x++){
        for (int y = x + 1; y < list.size; y++){
           System.out.println(list.get(x) + list.get(y);
        }
    }

Inner loop should start at outer loop's index + 1 and go on till the end of the list. This will work assuming you do not have duplicates in list

Also to compare strings, you would need to use .equals(). == will always evaluate to false if they are two different String instances i.e. :

String a = "apple" //Same value but twi different String instances
String b = "apple"
System.out.println(a==b) // Prints false
System.out.println(a.equals(b)) Prints true

== operator compares the object references not the value, where as .equals() compares the values in the two objects. So == will check if the two objects refer to the same String instance or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download