gpt4 book ai didi

java - 找到字符串数组的唯一值并保持顺序

转载 作者:行者123 更新时间:2023-12-01 22:48:20 26 4
gpt4 key购买 nike

我有一个 String[] ,其值如下:

line_str = "1,3,4,3,11,2,2,6,7"

我想找到独特的值(value)并保持值(value)的排列

unique_str="1,3,4,11,2,6,7"

我正在使用 HashSet 但输出是:

[1,6,7,4,11,3,2]

这是我的代码:

String line_str = "1,3,4,3,11,2,2,6,7";
String[] str_arr = line_str.split(",");
Set<String> uniqueValue = new HashSet<>(Arrays.asList(str_arr));
Toast.makeText(this, uniqueValue.toString(),Toast.LENGTH_LONG).show();

最佳答案

HashSet 将确保不重复,LinkedHashSet 将确保每个元素保持在其指定位置;

String line_str = "1,3,4,3,11,2,2,6,7";
String[] str_arr = line_str.split(",");
Set<Integer> uniqueNumbers = new LinkedHashSet<Integer>();
for(String num : str_arr) {
uniqueNumbers.add(Integer.parseInt(num));
}

如果您的输入有任何差异,那么您将需要处理它。

关于java - 找到字符串数组的唯一值并保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58465931/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com