0

I've an Arraylist variable

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
And
ArrayList<String> split;

Then i used nodes.add(split);

And I've a result of ArrayList like this

[[hasAttribute, hasPart, has_RP-09, has_RP-10], [hasAttribute, hasPart, has_RP-03, has_RP-06]]

How to combine that to be a result like this

[hasAttribute, hasPart, has_RP-09, has_RP-10, has_RP-03, has_RP-06]

Thank you guys for the answer.

Phatter
  • 23
  • 2
  • 7

2 Answers2

2

You can loop over the individual list and add all of its elements to a Set:

ArrayList<ArrayList<String>> nodes = new ArrayList<ArrayList<String>>();
...
Set<String> set = new HashSet<String>();
for (ArrayList<String> list : nodes) {
    set.addAll(list);       
}

If you want to preserve the order, use a LinkedHashSet instead of the HashSet.

M A
  • 71,713
  • 13
  • 134
  • 174
0

Java 8 can help you a lot.

Set<String> combined = nodes.stream().flatMap(n -> n.stream()).collect(Collectors.toSet());
Jacky
  • 8,619
  • 7
  • 36
  • 40