상세 컨텐츠

본문 제목

[리스트를 맵으로 변환] 스트림

자바

by esoesmio 2023. 4. 7. 12:18

본문

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
////////스트림을 리스트에 다시 담기



public class ㅋ9 {



    public static void main(String[] args) {
        List<creditcard> cd = new ArrayList<>();

        cd.add(new creditcard("a"));
        cd.add(new creditcard("b"));
        cd.add(new creditcard("c"));
        cd.add(new creditcard("d"));
        cd.add(new creditcard("e"));

    //특정 카드사의 카드만 뽑아서 collect로 수집

        //리스트로 다시 바꿈
/////////////////리스트를 맵으로 변환
List<creditcard> acom = cd.stream().filter(a->a.getName().equals("a")).toList();
        System.out.println(acom);

        Map<String, Integer> cardmap = new HashMap<>();
        cardmap = cd.stream().collect(Collectors.toMap(a->a.getName(), a->1));

        System.out.println(cardmap);



    }


}

class creditcard{


    @Override
    public String toString() {
        return "creditcard{" +
                "name='" + name + '\'' +
                '}';
    }

    String name;


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

    public void setName(String name) {
        this.name = name;
    }
}

관련글 더보기

댓글 영역