AdSense

網頁

2019/6/12

Java 計算List中某個元素出現的次數

若要計算List中某特定元素有幾個,可使用Collections.frequency(Collection<?> c, Object o)


第一個餐數c為要計算的集合物件,所以只要是Collection的子類都可以,第二個參數o為要計算的元素。

List<Integer> list = Arrays.asList(1,1,1,2,3,3,4,5);

System.out.println(Collections.frequency(list, 1)); // 3
System.out.println(Collections.frequency(list, 2)); // 1
System.out.println(Collections.frequency(list, 3)); // 2
List<String> list = Arrays.asList("A","B","B","C","C","C");

System.out.println(Collections.frequency(list, "A")); // 1
System.out.println(Collections.frequency(list, "B")); // 2
System.out.println(Collections.frequency(list, "C")); // 3

如果是自訂類別記得要覆寫equals()hashCode()

public class Main {

    public static void main(String[] args) {

        List<People> list = Arrays.asList(
                new People("Mario"),
                new People("Mario"),
                new People("Luigi"),
                new People("Toad"),
                new People("Toad"),
                new People("Toad")
            );

        System.out.println(Collections.frequency(list, new People("Mario"))); // 2
        System.out.println(Collections.frequency(list, new People("Luigi"))); // 1
        System.out.println(Collections.frequency(list, new People("Toad"))); // 3
        
    }

}

class People {
    private String name;
    
    public People(String name) {
        this.name = name;
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) return true;
        if (!(o instanceof People)) {
            return false;
        }
        People p = (People) o;
        return p.name.equals(name);
    }

    @Override
    public int hashCode() {
        int result = 17;
        result = 31 * result + name.hashCode();
        return result;
    }

}

沒有留言:

AdSense