我在使用应用程序时遇到问题。
我想将我的字符串移入此 ArrayList
.
我的字符串包含类似 15 17 18 110 113 的数字(从 1 到 200 的数字)。 我在一个字符串中有大约 80 个数字,例如:
I/System.out: 15 13 13 12 12 11 11 21 21 39 39 38 38 40 40 41 41 42 42 43 43 74 74 75 75 76 76 77 77 78 78 80 80 99 99 100 100 102 102 103 103 105 105 104
虽然我有List<String> tmpPath = new ArrayList<>();
我尝试了两种不同的方法:
1.
public void transferStringToArray(string s1){
for(int i = 0; i < s1.length(); i++){
int extra = 0;
if(s1.charAt(i) != ' '){
String x = Character.toString(s1.charAt(i));
tmpPath.add(extra, x);
else extra++;
}
}
输出是:
I/System.out: [4, 0, 1, 5, 0, 1, 5, 0, 1, 3, 0, 1, 3, 0, 1, 2, 0, 1, 2, 0, 1, 0, 0, 1, 0, 0, 1, 9, 9, 9, 9, 0, 8, 0, 8, 8, 7, 8, 7, 7, 7, 7, 7, 6, 7, 6, 7, 5, 7, 5, 7, 4, 7, 4, 7, 3, 4, 3, 4, 2, 4, 2, 4, 1, 4, 1, 4, 0, 4, 0, 4, 8, 3, 8, 3, 9, 3, 9, 3, 1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 3, 1, 3, 1, 5, 1]
(数字是从最后一个数字打印到第一个数字,这与我的假设是错误的)
2.
public void transferStringToArray(string s1){
for(int i = 0; i < s1.length(); i++)
if(s1.charAt(i) != ' '){
String x = Character.toString(s1.charAt(i));
tmpPath.add(x);
}
其中输出顺序良好,但一个数字表示数组的一个索引。
I/System.out: [1, 5, 1, 3, 1, 3, 1, 2, 1, 2, 1, 1, 1, 1, 2, 1, 2, 1, 3, 9, 3, 9, 3, 8, 3, 8, 4, 0, 4, 0, 4, 1, 4, 1, 4, 2, 4, 2, 4, 3, 4, 3, 7, 4, 7, 4, 7, 5, 7, 5, 7, 6, 7, 6, 7, 7, 7, 7, 7, 8, 7, 8, 8, 0, 8, 0, 9, 9, 9, 9, 1, 0, 0, 1, 0, 0, 1, 0, 2, 1, 0, 2, 1, 0, 3, 1, 0, 3, 1, 0, 5, 1, 0, 5, 1, 0, 4]
您是否有任何想法如何将完整数字移动为一个索引并用空格分隔?
另外我还有一个问题: 如何删除所有重复的数字?我知道,数字会打印一次或两次,但结果中我必须有唯一的数字。
最佳答案
您需要做的就是使用空格s.split("\\s+")
进行split
,然后将结果放入Set
像这样:
Set<String> set = new HashSet<>(Arrays.asList(s.split("\\s+")));
或者如果你想维持订单,你可以使用:
Set<String> set = new LinkedHashSet<>(Arrays.asList(s.split("\\s+")));
如果您只想使用 List 而没有其他,那么您可以使用 distinct
,如下所示:
List<String> set = Arrays.stream(s.split("\\s+"))
.distinct()
.collect(Collectors.toList());
输出
[15, 13, 12, 11, 21, 39, 38, 40, 41, 42, 43, 74, 75, 76, 77, 78, 80, 99, 100, 102, 103, 105, 104]
关于java - 如何将数字字符串转换为不同的 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59534770/