Home > database >  How to convert List<Set<String>> to List<List<String>> in java?
How to convert List<Set<String>> to List<List<String>> in java?

Time:11-29

How can we convert List<Set> to List<List> in java easily? Context: I came across this issue where I have generated List<Set> while in function return expects List<List>.

CodePudding user response:

Do you care about order in the Sets? If you do, you'll have to make sure you don't have them as Sets in the first place. If you don't, you can use the Java 8 streams API:

list.stream().map(ArrayList::new).collect(Collectors.toList());

Or a for loop.

CodePudding user response:

To convert from a Set to a List, you can simply do new ArrayList<>(mySet). So you can do something like:

Set<String> set1 = new HashSet<>(Arrays.asList("a", "b"));
Set<String> set2 = new HashSet<>(Arrays.asList("c", "d"));
List<List<String>> result = new ArrayList<List<String>>();
List<Set<String>> listOfSets = new ArrayList<>();
listOfSets.add(set1);
listOfSets.add(set2);
for (Set<String> set : listOfSets) {
    result.add(new ArrayList<>(set));
}
System.out.println(result);

Output: [[a, b], [c, d]]

  • Related