我如何在Java中对我的收藏进行分类,以便在第一个索引上找到给定的元素



我有Java中的自定义结构集合:

private List<CustomStructure> items = new ArrayList<>();

i也有一种方法,即在单个对象CustomStructure上调用时 - 返回其中一个字段的值。此方法称为.getDirectName()

我需要一种通过我的列表 items的方法,并在第一个索引上放置了将名称等于某些输入字符串的元素。

因此,如果列表包含以下元素:

first
 |
  --> getDirectName() -> one
second
 |
  --> getDirectName() -> two
third
 |
  --> getDirectName() -> three
fourth
 |
  --> getDirectName() -> four

,该方法将three作为输入参数,结果应为:

third first second fourth

在Java 8中最有效的方法是什么?

如果物品可能发生多次出现,或者您就像花式Java 8功能,您可以使用

list.sort(Comparator.comparing(itemToBeMovedToFront::equals).reversed());

(如果没有reversed(),它将将它们移至末端)。

但是,如果最多可以发生Java 2变体

Collections.rotate(list.subList(0, list.indexOf(itemToBeMovedToFront)+1), 1);

可能更有效。

调整他们使用列表元素的属性产生

list.sort(Comparator.comparing(
  (CustomStructure cs) -> cs.getDirectName().equals(dirNameToBeMovedToFront)).reversed());

对于第一个变体

IntStream.range(0, list.size())
    .filter(ix -> list.get(ix).getDirectName().equals(dirNameToBeMovedToFront))
    .findAny()
    .ifPresent(index -> Collections.rotate(list.subList(0, index+1), 1));

第二个。现在,即使是第二个变体都使用Java 8功能,因为在Java 8…

之前找到具有特定属性的元素并不是那么整洁。
public static void relocateToTop(List<CustomStructure> items, String directName) {
    for (Iterator<CustomStructure> iterator = items.iterator(); iterator.hasNext(); ) {
        CustomStructure item = iterator.next();
        if(Objects.equals(item.getDirectName(), directName)) {
            iterator.remove();
            items.add(0, item);
            return;
        }
    }
}

[edit]

请记住,即使要删除其中一个,也要始终使用Iterator通过List迭代,因为如果您的列表类型为LinkedList,则使用常规for迭代迭代,并通过其索引获取算法的算法O算法o(n^2)。例如这样的事情:

for(int i = 0; i < list.size(); i++)
    System.out.println(list.get(i));

如果列表是LinkedList,则在get方法的每个调用中,我们都有一个从LinkedList的头部循环到达I-th元素,因为与ArrayList不同,LinkedList不通过其索引存储元素。

如果您使用的是Java 8(如暗示),您始终有Stream::filter方法可以找到您的东西。

final List<CustomStructur> filtered = items.stream()
        .filter(item -> givenName.equals(item.getDirectName()))
        .collect(Collectors.toList());
items.removeAll(filtered);
items.addAll(0, filtered);

相关内容

最新更新