本文介绍了Java 8从列表中删除大小写无关的重复字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不考虑每个单词的大小写的情况下从字符串列表中删除重复的元素,例如考虑以下代码片段

How can we remove duplicate elements from a list of String without considering the case for each word, for example consider below code snippet

    String str = "Kobe Is is The the best player In in Basketball basketball game .";
    List<String> list = Arrays.asList(str.split("\\s"));
    list.stream().distinct().forEach(s -> System.out.print(s+" "));

这仍然提供与下面相同的输出,这很明显

This still gives the same output as below, which is obvious

Kobe Is is The the best player In in Basketball basketball game .

我需要如下结果

Kobe Is The best player In Basketball game .

推荐答案

从字面上考虑您的问题,无论列表中是否有大小写,都删除重复的字符串",您可以使用

Taking your question literally, to "remove duplicate strings irrespective of case from a list", you may use

// just for constructing a sample list
String str = "Kobe Is is The the best player In in Basketball basketball game .";
List<String> list = new ArrayList<>(Arrays.asList(str.split("\\s")));

// the actual operation
TreeSet<String> seen = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
list.removeIf(s -> !seen.add(s));

// just for debugging
System.out.println(String.join(" ", list));

这篇关于Java 8从列表中删除大小写无关的重复字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 11:15