Home > database >  Java : How to convert from Set to List while specifying first element of List
Java : How to convert from Set to List while specifying first element of List

Time:07-05

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);
}

Is there a way to convert from a Set to a List and guaranteeing element1 is the first element in the List? I do not care about the ordering for the rest of the elements in the List only the very first element. I could remove element1 from the Set then add it to the List then add the rest of the element. I'm just wondering what is the cleanest way to do this.

CodePudding user response:

convert from a Set to a List and guaranteeing element1 is the first element in the List?

For that, you need to use a LinkedHashSet which is capable of maintaining the order of elements instead of HashSet.

Set<Foo> fooSet = new LinkedHashSet<>();

fooSet.add(element1);
fooSet.add(element2);
fooSet.add(element3);

List<Foo> fooList = new LinkedList<>(fooSet);

And since you've added the tag it seems like use you were thinking of stream-based solution, I would point out that there's no need to create a stream and utilize a collector just in order to dump the same data without any changes into a list.

Sure, no one has a power to prohibit you to right such line:

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

But it would be a misuse of streams.

  • Related