I'm trying to create sublists from a list based on the suffix.
public class Test {
public static void main(String args[]) {
List<List<String>> subList = new ArrayList<List<String>>();
List<String> myList = new ArrayList<String>();
myList.add("Text_1");
myList.add("XYZ_3");
myList.add("ABC_1");
myList.add("Text_2");
myList.add("Text_3");
myList.add("XYZ_1");
myList.add("XYZ_2");
myList.add("ABC_2");
for (String item : myList) {
List<String> tempList = new ArrayList<String>();
String suffix = item.substring(item.lastIndexOf("_"));
tempList.add(item);
for (String value : myList) {
if (value.endsWith(suffix) && !tempList.contains(value)) {
tempList.add(value);
}
}
System.out.println(tempList);
}
}
}
I'm expecting like below
// Text_1, ABC_1, XYZ_1
// Text_2, ABC_2, XYZ_2
// Text_3, XYZ_3
But the actual is
[Text_1, ABC_1, XYZ_1]
[XYZ_3, Text_3]
[ABC_1, Text_1, XYZ_1]
[Text_2, XYZ_2, ABC_2]
[Text_3, XYZ_3]
[XYZ_1, Text_1, ABC_1]
[XYZ_2, Text_2, ABC_2]
[ABC_2, Text_2, XYZ_2]
Any help is appreciated. Thanks
There are several problems with your code:
1) you build the tempList on every item, so while the result are correct, you will see them for every item in myList. you need to "remember" each suffix you process so that you won't process it again. a
HashMap
will do the job2) if you want tempList to have uniqe values, use
Set
here is the complete solution
output: