Reputation: 421
Is there a way to convert a List<Set<String>> mainList
to a plain List, without iterating over elements?
For example this one has value:
mainList = {ArrayList@705} size = 2
0 = {HashSet@708} size = 3
0 = "A2"
1 = "A1"
2 = "A3"
1 = {HashSet@709} size = 3
0 = "A6"
1 = "A5"
2 = "A7"
I would like to have a new list like so:
list = A2,A1,A3, A6, A5, A7
Upvotes: 0
Views: 312
Reputation: 729
If you are only curious about not using iterator, you can use simple for each loop to solve the purpose
List<Set<String>> hs = null ; // Actual given List<Set<String>
ArrayList<String> arrayList = new ArrayList<String>(); // Plain List that will contain all the strings
for(Set<String> set :hs) {
arrayList.addAll(new ArrayList<String>(set)); // adding all the elements in list from hashset
}
and with using streams(java 1.8 and above) in this way
List<Set<String>> list = null ;
List<String> al = hs.stream().flatMap(Set::stream).collect(Collectors.toList());
but can you please explain why you don't want to use iterators?
Upvotes: 2
Reputation: 12937
If you are using java 1.8 and above, then you can use streams but it will still use an internal iterator. Here is an example:
List<String> list = mainList.stream() // create stream
.flatMap(Set::stream) // convert Set<String> to Stream
.collect(Collectors.toList()); // collect to new ArrayList
Upvotes: 1
Reputation: 44240
You can't. Ordinarily, the only way to copy n
things is to iterate over each of them.
The only way to avoid iterating over elements would be a lower-level operation like an array copy.
An ArrayList
would do this (others like LinkedList
would not) but no Set
implementation in the JDK provides its own toArray
implementation. They all use AbstractCollection.toArray
which internally iterates over all of the elements.
If you implemented or found an array-based Set
implementation (which would almost certainly not be an optimal Set
, however) then you could flatten an ArrayList<ArraySet<String>>
by using a series of array copies without iterating over the elements.
Upvotes: 1