我有两个数组列表。
一个是整数数组,另一个是字符串数组。在这里,我需要对整数数组值进行排序,以便从最高值到最低值进行排序。此时,我还需要从字符串数组中移动位置。
例如:
字符串数组:注册和行政主管,网页设计,IT -软件工程师,会计,网络工程师Int Array : 4,2,2,6,2
但我需要上面的结果。
字符串数组:会计、注册及行政主管、IT -软件工程师、网络工程师、网页设计Int数组: 6、4、2、2、2
需要对整数数组进行排序,同时还要改变字符串数组的位置,如果整数数组中出现相同的值,则需要按字母顺序排序。我该怎么做?
有最近的路吗?
发布于 2016-07-01 17:45:01
我希望这会对你有所帮助:
int[] intArray = new int[] { 4, 2, 2, 6, 2 };
String[] strArray = new String[] { "Register & Head of Administration", "Web Designing", "IT - Software Engineer", "Accountant", "Network Engineer" };
int tmp0 = 0;
String tmp1 = "";
for (int i = 0; i < intArray.length; i++) {
for (int j = i + 1; j < intArray.length; j++) {
if (intArray[j] > intArray[i]) {
// swap in int-Array
tmp0 = intArray[i];
intArray[i] = intArray[j];
intArray[j] = tmp0;
// swap in string-Array
tmp1 = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp1;
} else if (intArray[j] == intArray[i]) {
// sorts alphabetically
if (strArray[j].compareTo(strArray[i]) < 0) {
tmp1 = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp1;
}
}
}
}
//output
for (int k = 0; k < intArray.length; k++) {
System.out.println(strArray[k] + " " + intArray[k]);
}
输出:
Accountant 6 Register & Head of Administration 4 IT - Software Engineer 2 NetworkEngineer 2 Web Designing 2
发布于 2016-07-01 17:12:49
List<Pair<String, Integer>> data= new ArrayList<Pair<String, Integer>();
data.add(new Pair("Register & Head of Administration", 4));
...
data.add(new Pair("Network Engineer", 2));
Collections.sort(data, new Comparator<Pair<String, Integer>>() {
@Override
public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) {
// TODO: implement your logic here, e.g.
return o1.second.compareTo(o2.second);
}
发布于 2016-07-01 17:32:00
为什么不使用第三个类来对所有字符串进行加权分组。
创建一个比较器来排序WeightString,然后使用Stream API来使用数据。
public class WeightString {
public String value;
public int weight;
public WeightString(String value, int weight) {
this.value = value;
this.weight = weight;
}
}
public Comparator<WeightString> mWeightStringComparator =
(o1, o2) -> Integer.compare(o1.weight, o2.weight);
// in code
WeightString[] weightStrings = new WeightString[]{
new WeightString("a", 12),
new WeightString("b", 1),
new WeightString("c", 8),
new WeightString("d", 4)
};
Stream<WeightString> stringStream = Arrays.stream(weightStrings);
stringStream.sorted(mWeightStringComparator);
WeightString[] orderedWeightStrings = (WeightString[]) stringStream.toArray();
//orderedWeightStrings : [b,d,c,a]
https://stackoverflow.com/questions/38141218
复制相似问题