Java - 根据另一个数组的值对一个数组进行排序? [英] Java - Sort one array based on values of another array?

查看:677
本文介绍了Java - 根据另一个数组的值对一个数组进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串数组,它是来自外部代码的类的实例,我宁愿不改变。

I have an array of Strings that are instances of a class from external code that I would rather not change.

我还有一个生成的int数组通过调用每个对象上的函数。所以我有

I also have an array of ints that was generated by calling a function on each object. So I have

A: [string1,string2,string3]

B: [40,32,34]

如何轻松地对A进行排序,使其按B的值排序。我有可用的提升。我想按顺序对A进行排序:

How do I easily sort A such that it is sorted in by the values of B. I have boost available. I want to sort A such that it is in the order:

[string2, string3, string1]

在javascript中你可以这样做:

In javascript you could do this like:

B.sort(function(a,b){return A[B.indexOf(a)] < A[B.indexOf(b)];});


推荐答案

我使用Comparator接口解决了这个问题。

I solved this problem by using Comparator interface.

 import java.util.Comparator;
 import java.util.Collections;
 import java.util.List;
 import java.util.Arrays;


 public class ComparatorDemo {

 public static void main(String[] args) {
    List<Area> metaData = Arrays.asList(
            new Area("Joe", 24),
            new Area("Pete", 18),
            new Area("Chris", 21),
            new Area("Rose",21)
    );

    Collections.sort(metaData, new ResultComparator());
    for(int i =0 ;metaData.size()>i;i++)
             System.out.println(metaData.get(i).output);


  }
 }


 class ResultComparator implements Comparator<Area> {
     @Override
     public int compare(Area a, Area b) {
         return a.result < b.result ? -1 : a.result == b.result ? 0 : 1;
     }
 }

 class Area{
   String output;
   int result;

Area(String n, int a) {
    output = n;
    result = a;
     }
 }

这篇关于Java - 根据另一个数组的值对一个数组进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆