简体   繁体   English

从java集合中的给定列表中删除除最后一个元素之外的所有元素

[英]Deletes all but the last element from a given list in java collections

Implement a method below which deletes all but the last element from a given list.在下面实现一个方法,该方法删除给定列表中除最后一个元素之外的所有元素。

import java.util.ArrayList;
import java.util.List;
public class MyClass {
public static void allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   for (int k : list)
   {
      set.remove(0, -2);
   }
   return set;
}

I just started programming and this is a practice question and I was wondering if this type of solution would make sense.我刚开始编程,这是一个练习题,我想知道这种类型的解决方案是否有意义。 I started from the first array block(0) and it stops at the the array block before the last element(-2) and removes it, only keeping the last element and returning it at the end.我从第一个数组块(0)开始,它在最后一个元素(-2)之前的数组块处停止并删除它,只保留最后一个元素并在最后返回它。

Pseudo code:伪代码:

while (list.length() > 1)
{
    list.removeElementAt(0);
}

Change the return type void to List<String>return类型void更改为List<String>

public static List<String> allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   String last=set.remove(set.size() - 1);
   set.clear();
   set.add(last);
   return set;
}

Or或者

public static List<String> allButLast(List<String> list)
{
   List<String> set = new ArrayList<String>();
   set.subList(0, set.size() - 1).clear();
   return set;
}

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

相关问题 从Java util列表读取时,为什么所有元素都返回最后一个元素? (概括) - When reading from a java util List, why do all elements return the last element? (generalized) 从java中的给定列表中获取每个月的最后一天 - Getting last day of each month from given list in java 最后添加的元素将覆盖列表中的所有对象。 爪哇 - The last element added overwrites all the objects in the List. Java 如何在JAVA中报告列表中最后一个元素的所有并列位置 - how to report all tied positions for the last element in the list in JAVA java中mongo数据库中所有集合的列表 - List of all collections in mongo database in java 串联到Java列表中的最后一个元素 - concatenate to last element in list in java Java从PriorityQueue中找到的节点列表中获取最后一个元素 - Java get last element from List of nodes found within PriorityQueue 我无法从Java中的数组列表中删除最后一个元素 - I can't delete last element from array list in Java java集合,用于从庞大的列表中检索值 - java Collections for retrieving values from a huge list 在 Java 中将较大的集合(集合、数组、列表)拆分为较小的集合,并跟踪返回的最后一个集合 - Split larger collection (Collections, Arrays, List) into smaller collections in Java and also keep track of last one returned
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM