集合中的Java过滤

时间:2014-02-04 18:33:41

标签: java collections

我有一个对象列表,如下所示,

Emp e1  = new Emp(10,"Anitha",1000,"AE");
Emp e2  = new Emp(20,"Chaitanya",2000,"SE");
Emp e3  = new Emp(30,"Chaitanya",3000,"SE");
Emp e4  = new Emp(40,"Deepthi",2100,"AE");
Emp e5  = new Emp(50,"Deepthi",2200,"CE");
Emp e6  = new Emp(60,"Deepthi",2300,"BE");
Emp e7  = new Emp(70,"Anitha",2300,"BE");
Emp e8  = new Emp(80,"Anitha",2400,"ME");
Emp e9  = new Emp(90,"Sita",2200,"CE");
Emp e10 = new Emp(100,"Hari",2200,"CE");
Emp e11 = new Emp(110,"Krishna",2200,"CE");

我想过滤唯一名称上的值,并过滤相同的名称,如

1.on唯一名称:输出应为

(50,"Deepthi",2200,"CE")
(100,"Hari",2200,"CE")
(110,"Krishna",2200,"CE")

并分享相同的名称:

像输出一样

(10,"Anitha",1000,"AE")
(70,"Anitha",2300,"BE")
(80,"Anitha",2400,"ME")
(20,"Chaitanya",2000,"SE");
(30,"Chaitanya",3000,"SE");
(40,"Deepthi",2100,"AE");
(50,"Deepthi",2200,"CE");
(60,"Deepthi",2300,"BE");

使用收藏.... 有人能帮助我吗?

先谢谢。 Nithya

3 个答案:

答案 0 :(得分:3)

如果您使用的是java 8,请跳到最后!

我可能会创建一个map来做这件事,但看起来你是Java的新手,所以我将描述更基本的方法。

您应首先创建一个列表(arraylist),如下所示:

// create an arraylist (list based on an array)
List<Emp> emps = new ArrayList<Emp>();

然后您可以将对象添加到列表中:

emps.add(new Emp(10,"Anitha",1000,"AE"));
emps.add(new Emp(20,"Chaitanya",2000,"SE"));
.
.

现在你可以开始过滤了!

因此,假设您在类getName()中有Emp方法,您可以编写如下函数:

// this function takes a list and a name, and filters the list by the name
public static List<Emp> filterEmpsByName(List<Emp> emps, String name){
    // a place to store the result
    List<Emp> result = new ArrayList<Emp>();
    // iterate over the list we got
    for (Emp emp: emps){
        // save only the elements we want
        if (emp.getName().equals(name)){
            result.add(emp);
        }
    }
    return result;
}

现在,过滤将是调用该函数的一个简单问题:

// print to standard output the result of our function on the "main" list `emp` with name "Anitha"
for (Emp emp : filterEmpsByName(emps, "Anitha")){
    System.out.println(emp.toString()); // make sure toString() is overridden in Emp class
}

现在第二部分有点棘手:

// this function takes a list and a name, and filters the list by the name
public static List<Emp> getDistinctlyNamedEmps(List<Emp> emps, String name) {
    // this time we use a map which is A LOT faster for this kind of operation

    Map<String, Emp> result = new HashMap<String, Emp>();
    // iterate over the list we got
    for (Emp emp : emps) {
        // save only the elements we want
        if (result.get(emp.getName()) == null ) {
            result.put(emp.getName(), emp);
        }
    }

    // convert map to list - not mandatory if you can use the map as is...
    return new ArrayList<Emp>(result.values());
}

请注意,您还可以编写一个comparator来使用名称/任何其他属性来比较对象,但这超出了此评论的范围: - )

把整个事情放在一起:

主要课程:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {

    public static void main(String[] args) {
        // create an [arraylist][4] (list based on an array)
        List<Emp> emps = new ArrayList<Emp>();

        emps.add(new Emp(10, "Anitha", 1000, "AE"));
        emps.add(new Emp(20, "Chaitanya", 2000, "SE"));

        // print to standard output the result of our function on the "main"
        // list `emp` with name "Anitha"
        System.out.println("filterEmpsByName(emps, \"Anitha\") output:");
        for (Emp emp : filterEmpsByName(emps, "Anitha")) {
            System.out.println(emp.toString()); // make sure toString() is
                                                // overridden in Emp class
        }

        // print to standard output the result of our second function on the "main"
        // list `emp`
        System.out.println("getDistinctlyNamedEmps(emps) output:");
        for (Emp emp : getDistinctlyNamedEmps(emps)) {
            System.out.println(emp.toString()); // make sure toString() is
                                                // overridden in Emp class
        }
    }

    // this function takes a list and a name, and filters the list by the name
    public static List<Emp> filterEmpsByName(List<Emp> emps, String name) {
        // a place to store the result
        List<Emp> result = new ArrayList<Emp>();
        // iterate over the list we got
        for (Emp emp : emps) {
            // save only the elements we want
            if (emp.getName().equals(name)) {
                result.add(emp);
            }
        }
        return result;
    }

    // this function takes a list and a name, and filters the list by the name
    public static List<Emp> getDistinctlyNamedEmps(List<Emp> emps) {
        // this time we use a map which is A LOT faster for this kind of
        // operation

        Map<String, Emp> result = new HashMap<String, Emp>();
        // iterate over the list we got
        for (Emp emp : emps) {
            // save only the elements we want
            if (result.get(emp.getName()) == null) {
                result.put(emp.getName(), emp);
            }
        }

        // convert map to list - not necessary
        return new ArrayList<Emp>(result.values());
    }

}

部分Emp类:

public class Emp {

    private String name;

    public Emp(int stubi, String name, int j, String stubs) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public String toString() {
        return "[" + this.name + "]";
    }
}

Java 8:

Java 8具有lambda expressions(匿名函数),它是许多其他语言中用于过滤和其他操作的简洁工具。

您可以详细了解如何使用它们here

答案 1 :(得分:0)

这不是集合,虽然它是传统意义上的“列表”,但它不是java.util.ArrayList

为此,您可以尝试:

ArrayList<Emp> employeeList = new ArrayList<Emp>();

employeeList.add(new Emp(10,"Anitha",1000,"AE"));
// repeat

答案 2 :(得分:0)

据我所知,答案直到现在才假设任务是搜索查找特定名称,或者查找具有唯一名称的元素 - 我认为这不是问的问题对于。

为了按照原始问题中描述的方式过滤列表,可以创建一个从“密钥”(即本例中的“名称”)到共享此元素的元素列表的映射键。使用此地图,可以轻松找到

  • 每个键的一个元素,仅在所有元素中出现一次
  • 具有在所有元素中至少出现两次的键的所有元素的列表

这些任务非常相似,可能有进一步的概括,但这里有一种方法可以实现:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class CriterionFilter
{
    public static void main(String[] args)
    {
        List<Emp> list = new ArrayList<Emp>();
        list.add(new Emp(10,"Anitha",1000,"AE"));
        list.add(new Emp(20,"Chaitanya",2000,"SE"));
        list.add(new Emp(30,"Chaitanya",3000,"SE"));
        list.add(new Emp(40,"Deepthi",2100,"AE"));
        list.add(new Emp(50,"Deepthi",2200,"CE"));
        list.add(new Emp(60,"Deepthi",2300,"BE"));
        list.add(new Emp(70,"Anitha",2300,"BE"));
        list.add(new Emp(80,"Anitha",2400,"ME"));
        list.add(new Emp(90,"Sita",2200,"CE"));
        list.add(new Emp(100,"Hari",2200,"CE"));
        list.add(new Emp(110,"Krishna",2200,"CE"));

        Function<Emp, String> keyFunction = new Function<Emp, String>()
        {
            @Override
            public String apply(Emp s)
            {
                return s.getName();
            }
        };
        List<Emp> fiteredOnUnique = filterOnUnique(list, keyFunction);
        System.out.println("Filtered on unique:");
        print(fiteredOnUnique);

        List<Emp> filteredOnSame = filterOnSame(list, keyFunction);
        System.out.println("Filtered on same:");
        print(filteredOnSame);
    }

    private static void print(Iterable<?> elements)
    {
        for (Object element : elements)
        {
            System.out.println(element);
        }
    }

    /**
     * Create a map that maps the keys that are provided for the given
     * elements to the list of elements that have this key
     *
     * @param elements The input elements
     * @param keyFunction The key function
     * @return The map
     */
    private static <T, K> Map<K, List<T>> map(
        Iterable<? extends T> elements, Function<? super T, K> keyFunction)
    {
        Map<K, List<T>> map = new HashMap<K, List<T>>();
        for (T t : elements)
        {
            K key = keyFunction.apply(t);
            List<T> list = map.get(key);
            if (list == null)
            {
                list = new ArrayList<T>();
                map.put(key, list);
            }
            list.add(t);
        }
        return map;
    }

    /**
     * Uses the given key function to compute the keys associated with the
     * given elements, and returns a list containing the element of
     * the given sequence that have unique keys
     *
     * @param elements The input elements
     * @param keyFunction The key function
     * @return The filtered list
     */
    private static <T, K> List<T> filterOnUnique(
        Iterable<? extends T> elements, Function<? super T, K> keyFunction)
    {
        List<T> result = new ArrayList<T>();
        Map<K, List<T>> map = map(elements, keyFunction);
        for (Entry<K, List<T>> entry : map.entrySet())
        {
            List<T> list = entry.getValue();
            if (list.size() == 1)
            {
                result.add(list.get(0));
            }
        }
        return result;
    }

    /**
     * Uses the given key function to compute the keys associated with the
     * given elements, and returns a list containing all elements of
     * the given sequence that have a key that occurs multiple times.
     *
     * @param elements The input elements
     * @param keyFunction The key function
     * @return The filtered list
     */
    private static <T, K> List<T> filterOnSame(
        Iterable<? extends T> elements, Function<? super T, K> keyFunction)
    {
        List<T> result = new ArrayList<T>();
        Map<K, List<T>> map = map(elements, keyFunction);
        for (Entry<K, List<T>> entry : map.entrySet())
        {
            List<T> list = entry.getValue();
            if (list.size() > 1)
            {
                result.addAll(list);
            }
        }
        return result;
    }



    /**
     * Interface for a generic function
     */
    static interface Function<S, T>
    {
        T apply(S s);
    }

}


class Emp
{
    private int i;
    private String name;
    private int j;
    private String whatever;

    public Emp(int i, String name, int j, String whatever)
    {
        this.i = i;
        this.name = name;
        this.j = j;
        this.whatever = whatever;
    }

    @Override
    public String toString()
    {
        return "Emp [i=" + i + ", name=" + name + ", j=" + j + ", whatever=" + whatever + "]";
    }

    String getName()
    {
        return name;
    }
}

(编辑:调整第一个案例,见原始问题的评论)