Java 如何将字符串放入数组中而不重复
我在下面有这段文字Java 如何将字符串放入数组中而不重复,java,Java,我在下面有这段文字 String text = "a b c a a b b b c d a z e q e m a m d z e" 我怎么能把它们放在这样的数组中呢 ArrayList<String> array = new ArrayList<>(); //array above should be has {"a","b","c","d","z","e","q","m"} ArrayList数组=新的ArrayList(); //上面的数组应该有{“a”、“b
String text = "a b c a a b b b c d a z e q e m a m d z e"
我怎么能把它们放在这样的数组中呢
ArrayList<String> array = new ArrayList<>();
//array above should be has {"a","b","c","d","z","e","q","m"}
ArrayList数组=新的ArrayList();
//上面的数组应该有{“a”、“b”、“c”、“d”、“z”、“e”、“q”、“m”}
如何操作?使用列表创建集合清除列表向列表中添加集合项
yourList.addAll(Arrays.asList(text.split(" ")));
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
yourList.addAll(Arrays.asList(text.split(“”));
Set Set=新哈希集(yourList);
yourList.clear();
yourList.addAll(set);
String text=“a b c a b b c d a z e q e m a m d z e”
ArrayList数组=新的ArrayList()
addAll(Arrays.asList(text.split(“”))
将
字符串
按空格拆分,从中创建一个字符串-这将删除重复项并保留元素顺序(因为不允许重复值,并且它使用重复值和方法。LinkedHashSet
还保留元素添加顺序)。然后使用其复制构造函数创建ArrayList
:
LinkedHashSet<String> set = Arrays.stream(text.split("\\s"))
.collect(Collectors.toCollection(LinkedHashSet::new));
List<String> list = new ArrayList<>(set);
LinkedHashSet=Arrays.stream(text.split(“\\s”))
.collect(Collectors.toCollection(LinkedHashSet::new));
列表=新的ArrayList(集合);
使用设置为“不重复”元素
String text = "a b c a a b b b c d a z e q e m a m d z e"
Set<String> set = new HashSet<String>();
or change DTRING TO CHAR
set .addAll(text);
String text=“a b c a b b c d a z e q e m a m d z e”
Set=newhashset();
或者将DTRING更改为CHAR
set.addAll(文本);
使用流的另一种方法:
String text = "a b c a a b b b c d a z e q e m a m d z e";
ArrayList<String> array = Pattern.compile(" ")
.splitAsStream(text)
.distinct()
.collect(Collectors.toCollection(ArrayList::new));
System.out.println(array);
String text=“a b c a b c d a z e q e m a m d z e”;
ArrayList数组=Pattern.compile(“”)
.splitAsStream(文本)
.distinct()
.collect(收集器.toCollection(ArrayList::new));
System.out.println(数组);
使用Set而不是ArrayList,b因为Set集合不包含重复的元素。@Kabir请向他解释Set而不是ArrayList的用法检查Set示例:text variable在哪里?这不会保留元素的顺序。