0

In List<MyObject> list = new ArrayList<>() i want to swap position of two (always) objects that have the same value in field name.

public class SiteDTO {
   private Long id;
   private String name;

// getters setters constructors

}

i know that best way to do that is using Collections.swap(list, 1, 2); where 1 and 2 are positions of objects to swap.

But how to find these indexes?

4
  • 1
    So there is only two equals objects? Commented Sep 23, 2019 at 12:30
  • indexOf(Object o) Commented Sep 23, 2019 at 12:31
  • @VishwaRatna That can only work when his class has the equals method overriden so that it returns true for name field. Commented Sep 23, 2019 at 12:33
  • Of course, the solutions given in isolation work fine. But perhaps the best course of action is to see what you're doing and avoid this manipulation all together (if at all possible). Commented Sep 23, 2019 at 13:19

2 Answers 2

1

You could iterate over the indices of the list and find those groups that are equals, then swap the positions of those that have exactly two elements:

List<SiteDTO> sites = Arrays.asList(new SiteDTO(1L, "1"), new SiteDTO(2L, "2"), new SiteDTO(3L, "1"));
Map<String, List<Integer>> groups = IntStream.range(0, sites.size()).boxed().collect(groupingBy(o -> sites.get(o).getName()));

for (List<Integer> positions : groups.values()) {

    if (positions.size() == 2)
        Collections.swap(sites, positions.get(0), positions.get(1));

}

System.out.println(sites);

Output

[SiteDTO{id=3, name='1'}, SiteDTO{id=2, name='2'}, SiteDTO{id=1, name='1'}]

Note: This works for the case you have multiple groups to swap.

Sign up to request clarification or add additional context in comments.

Comments

0

By simply iterating that list?

int firstIndex = -1;
int secondIndex = -1;

for (int i=0; i < yourList.size(); i++) {
  if (yourList.get(i).getName().equals(whatever)) {
    firstIndex = i;
    break;
  }

And then you could for example just iterate in reverse order to identify the second index.

Of course, the above only works when there are exactly two objects that have the same property value in your list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.