在Java中将数据从HashSet移动到ArrayList

时间:2012-11-29 18:18:04

标签: java list data-structures arraylist hashset

我在Java中有以下Set

Set< Set<String> > SetTemp = new HashSet< Set<String> >();

我希望将其数据移至ArrayList

ArrayList< ArrayList< String > > List = new ArrayList< ArrayList< String > >);

有可能吗?

5 个答案:

答案 0 :(得分:41)

将数据HashSet移至ArrayList

Set<String> userAllSet = new HashSet<String>(usrAllTemp);
List<String> usrAll = new ArrayList<String>(userAllSet);

此处usrAllTempArrayList,其中包含一些值。 相同方式usrAll(ArrayList)userAllSet(HashSet)获取值。

答案 1 :(得分:13)

你只需要循环:

Set<Set<String>> setTemp = new HashSet<Set<String>> ();
List<List<String>> list = new ArrayList<List<String>> ();
for (Set<String> subset : setTemp) {
    list.add(new ArrayList<String> (subset));
}

注意:您应该以小型大写字母启动变量名称以遵循Java约定。

答案 2 :(得分:1)

您可以使用addAll()

Set<String> gamesInstalledTemp = new HashSet< Set<String> >();
List<String> gamesInstalled = new ArrayList<>();
gamesInstalled.addAll(gamesInstalledTemp);

答案 3 :(得分:1)

我们有这些在java中将hashet转换为ararylist的方法

方法一:我们将hashset作为参数传入arraylist/list的构造函数中

Set<String> hs = new HashSet<String>();
hs.add("java");
hs.add("php");
hs.add("html");
List<String> list = new ArrayList<String>(hs);

方法二:遍历Hashset并一一添加列表中的元素

  for (String str : hs) {
    arraylist.add(str);
 }

方法:使用 arr.addAll() 方法

 With the help of addAll() you can add collection into list

参考:How to Convert HashSet to a List/ArrayList

答案 4 :(得分:0)

您可以使用Stream和Collector来做到这一点,我希望这是最简单的方法

listname = setName.stream().collect(Collectors.toList());