I don't know if I understand what you want well, But the looping you want must be done using nested loop, consider this code:
public static void main(String[] args) {
LinkedHashSet<String> freq = new LinkedHashSet<String>();
freq.add("pen");
freq.add("pencil");
freq.add("eraser");
freq.add("scale");
for (String item : freq) {
performeOperation(item, freq);
}
}
private static void performeOperation(String primeItem, LinkedHashSet<String> freq) {
for (String secondItem : freq) {
if (primeItem != secondItem) {
System.out.println(primeItem + ", " + secondItem);
}
}
}
Output sample:
pen, pencil
pen, eraser
pen, scale
pencil, pen
pencil, eraser
pencil, scale
eraser, pen
eraser, pencil
eraser, scale
scale, pen
scale, pencil
scale, eraser
If you don't need duplicate pairs, use this:
public static void main(String[] args) {
LinkedHashSet<String> freq = new LinkedHashSet<String>();
LinkedHashSet<String> param = new LinkedHashSet<String>();
freq.add("pen");
freq.add("pencil");
freq.add("eraser");
freq.add("scale");
param.addAll(freq);
for (String item : freq) {
param.remove(item);
performeOperation(item, param);
}
}
private static void performeOperation(String primeItem, LinkedHashSet<String> param) {
for (String secondItem : param) {
System.out.println(primeItem + ", " + secondItem);
}
}
Output sample:
pen, pencil
pen, eraser
pen, scale
pencil, eraser
pencil, scale
eraser, scale
Yes, it can be done using one LinkedHashSet
, but you have to use the LinkedHashSet
to maintains the insertion order of elements, so that this solution can work.
public static void main(String[] args) {
LinkedHashSet<String> freq = new LinkedHashSet<String>();
freq.add("pen");
freq.add("pencil");
freq.add("eraser");
freq.add("scale");
for (String item : freq) {
performeOperation(item, freq);
}
}
private static void performeOperation(String primeItem, LinkedHashSet<String> param) {
boolean flag = false;
for (String secondItem : param) {
if (flag) {
System.out.println(primeItem + ", " + secondItem);
} else if (primeItem.equals(secondItem)) {
flag = true;
}
}
}