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.

6
  • If the same value exists in both ArrayLists are they only added once to the COMBINED result ? Do they have to be in any specific order ? Commented Jun 11, 2015 at 18:02
  • So you want the union of two (or more) ArrayList<String> objects? Commented Jun 11, 2015 at 18:02
  • possible duplicate of Join two arrays in Java? Commented Jun 11, 2015 at 18:03
  • if you need all elements in one ArrayList. use Set<String> node=new HashSet();. and add node.addAll(split); Commented Jun 11, 2015 at 18:13
  • If you are going to combine them into a single array why do you keep them in separate arrays ? whay not add them to a single SET from the beginning ? Commented Jun 11, 2015 at 18:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Java 8 can help you a lot.

Set<String> combined = nodes.stream().flatMap(n -> n.stream()).collect(Collectors.toSet());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.