简体   繁体   English

如何在数组列表中交换具有相同值的两个对象的 position

[英]How to swap position of two objects with same values in Array List

In List<MyObject> list = new ArrayList<>() i want to swap position of two (always) objects that have the same value in field name.List<MyObject> list = new ArrayList<>()我想交换两个(总是)在字段名称中具有相同值的对象的 position。

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);我知道最好的方法是使用Collections.swap(list, 1, 2); where 1 and 2 are positions of objects to swap.其中 1 和 2 是要交换的对象的位置。

But how to find these indexes?但是如何找到这些索引呢?

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 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.注意:这适用于您有多个组要交换的情况。

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.当然,上述方法仅适用于您的列表中恰好有两个具有相同属性值的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM