CS/언어

[JAVA] ArrayList에서 특정 값을 가진 원소들 찾기

pythaac 2022. 1. 14. 20:19
package com.company;
import java.util.*;
import java.util.stream.Collectors;

class Obj{
    public Integer a;
    public String b;
    public Long c;

    Obj(Integer a, String b, Long c){
        this.a = a;
        this.b = b;
        this.c = c;
    }

    String print(){
        return "a=" + this.a + ", b=" + this.b + ", c=" + this.c;
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Obj> list = new ArrayList<>();

        list.add(new Obj(1, "1", (long)1));
        list.add(new Obj(2, "2", (long)2));
        list.add(new Obj(3, "3", (long)3));
        list.add(new Obj(1, "2", (long)3));
        list.add(new Obj(2, "3", (long)1));
        list.add(new Obj(3, "1", (long)2));

        // find
        Obj result =
                list.stream().filter(obj -> obj.a.equals(1)).findFirst().orElse(null);

        if (result != null)
            System.out.println("result : " + result.print());

        // findAll
        ArrayList<Obj> results =
                (ArrayList<Obj>) list.stream().filter(obj -> obj.a.equals(1)).collect(Collectors.toList());

        for(int i=0; i<results.size(); i++){
            System.out.println("results : " + results.get(i).print());
        }
    }
}
// 원소 하나 찾기
list.stream().filter( obj -> value.equals(obj.getMember() );
// 여러 원소 찾기
(ArrayList<Obj>) list.stream().filter( obj -> value.equals(obj.getMember() ).collect(Collectors.toList());

 

'CS > 언어' 카테고리의 다른 글

[Java] 이중 콜론 연산자 (::)  (0) 2022.03.31
[JAVA] Hash와 Thread-Safe  (0) 2022.01.19
[JAVA] Long에 대하여  (0) 2022.01.12
[JAVA] 자바의 다중상속  (0) 2022.01.11
[JAVA] POJO(Plain Old Java Object)  (0) 2022.01.06