Java程序从列表中删除重复元素
要从列表中删除重复项,代码如下-
示例
import java.util.ArrayList;import java.util.LinkedHashSet;
import java.util.Set;
public class Demo {
public static void main(String[] args){
ArrayList<String> list = new ArrayList<String>();
list.add("Jacob");
list.add("Gary");
list.add("Gary");
list.add("Harry");
list.add("Harry");
list.add("Kevin");
System.out.println("List = "+list);
Set<String> set = new LinkedHashSet<String>(list);
System.out.println("删除重复元素后的列表 = "+set);
}
}
输出结果
List = [Jacob, Gary, Gary, Harry, Harry, Kevin]删除重复元素后的列表 = [Jacob, Gary, Harry, Kevin]
示例
现在让我们来看另一个示例-
import java.util.ArrayList;import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Demo {
public static void main(String[] args){
List<String> list = new ArrayList<String> (Arrays.asList("Ryan","Kevin","Ryan","Harry","Mark","Mark"));
System.out.println("ArrayList = "+list);
List<String> list2 = list.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("更新了ArrayList,没有重复项 = "+list2);
}
}
输出结果
ArrayList = [Ryan, Kevin, Ryan, Harry, Mark, Mark]更新了ArrayList,没有重复项 = [Ryan, Kevin, Harry, Mark]
以上是 Java程序从列表中删除重复元素 的全部内容, 来源链接: utcz.com/z/362118.html