Java:如何在指定List的第一个元素时从Set转换为List


static void main(String[] args) {
List<Foo> fooList = new LinkedList<>();
Set<Foo> fooSet = new HashSet<>();
Foo element1 = new Foo("Element1");
Foo element2 = new Foo("Element2");
Foo element3 = new Foo("Element3");
fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);
CollectionUtils.addAll(fooList, fooSet);
}

是否有一种方法可以从Set转换为List并保证element1是List中的第一个元素?我不关心List中其他元素的顺序,只关心第一个元素。我可以从Set中删除element1,然后将其添加到List中,然后添加元素的其余部分。我只是想知道做这件事最干净的方法是什么。

Set转换为List,并保证element1List中的第一个元素?

为此,您需要使用能够维护元素顺序的LinkedHashSet而不是HashSet

Set<Foo> fooSet = new LinkedHashSet<>();
fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);
List<Foo> fooList = new LinkedList<>(fooSet);

既然你添加了标签java-stream,看起来你是在考虑基于流的解决方案,我要指出的是,这里没有需要创建一个和利用收集器只是为了把相同的数据没有任何变化成一个列表。

当然,没有人有权力禁止你这样做:

List<Foo> fooList = fooSet.stream().collect(Collectors.toList());

但是这将是一个误用流。

最新更新