通过参数值检索ArrayList对象

时间:2019-01-27 04:07:23

标签: java arraylist

我正在维护对象的排序ArrayList(通过覆盖here所示的add方法),其中每个对象都有2个属性:ab。如何检索a等于5的对象?

我无法使用地图,因为我要对列表进行排序的值必须能够接受重复项(这就是this answer在这里不适用的原因。)

代码:

 class TimeMap {
     List<MyType> list = new ArrayList<KVT>() {
        public boolean add(KVT mt) {
            int index = Collections.binarySearch(this, mt, new SortByTime());
            if (index < 0) index = ~index;
            super.add(index, mt);
            return true;
        }
    };
}
class KVT{//value-timestamp object
    String value;
    int timestamp;
    public VT(String v, int t){
        value=v;
        timestamp=t;
    }
}
class SortByTimestamp implements Comparator<KVT>{
    public int compare(KVT a, KVT b){
        return a.timestamp.compareTo(b.timestamp);
    }
}

2 个答案:

答案 0 :(得分:0)

我用Java8流编写了一个小示例,您可以通过对象的属性从ArrayList获取对象。

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Test> list = Arrays.asList(new Test(1, 2), new Test(5, 6), new Test(3, 4));

        Test test = list.stream().filter(obj -> obj.a == 5).findFirst().orElse(null);
        System.out.println(test.a);
    }
}

class Test {
    int a;
    int b;

    Test(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

希望这会给您一个想法

答案 1 :(得分:0)

这是一个展示timestamp进行检索的mcve以及其他一些增强功能:

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

public class TimeMap {

    private List<KVT> list;

    TimeMap() {
        list = new ArrayList<>() {
            @Override
            public boolean add(KVT mt) {
                super.add(mt); //add
                Collections.sort(this, new SortByTimestamp()); //resort after add
                return true;
            }
        };
    }

    boolean add(KVT mt){return list.add(mt);}

    KVT getByTimeStamp(int timestamp){
        for(KVT mt : list){
            if(timestamp == mt.timestamp)
                return mt;
        }
        return null;
    }

    //returns a copy of list
    List<KVT> getListCopy() { return new ArrayList<>(list) ;};

    //test 
    public static void main(String[] args) {
        TimeMap tm = new TimeMap();
        tm.add(new KVT("A", 2));
        tm.add(new KVT("B", -3));
        tm.add(new KVT("C", 1));
        System.out.println(tm.getListCopy());
        System.out.println(tm.getByTimeStamp(1));
    }
}

class KVT{
    String value;
    int timestamp;
    public KVT(String v, int t){
        value=v;
        timestamp=t;
    }

    @Override
    public String toString(){   return value+" ("+timestamp+")";}

    //todo add getters 
}

class SortByTimestamp implements Comparator<KVT>{

    @Override
    public int compare(KVT a, KVT b){
        //compareTo can not be applied to primitives
        return Integer.valueOf(a.timestamp).compareTo(b.timestamp);
    }
}