package japan.example.test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import lombok.Data; public class StreamTests { public static void main(String[] args) { StreamTests test = new StreamTests(); test.test(test.data()); } public List<ResponseData> data() { ResponseData data = new ResponseData(); data.serialno = "0011"; data.setStatus("succ"); List<ResponseData> list = new ArrayList<>(); list.add(data); data = new ResponseData(); data.setSerialno("0011"); data.setStatus("fail"); list.add(data); data = new ResponseData(); data.setSerialno("0012"); data.setStatus("wait"); list.add(data); return list; } public void test(List<ResponseData> dataarray) { Map<String, List<String>> counting = dataarray.stream(). collect(Collectors.groupingBy(ResponseData::getSerialno, Collectors.mapping(ResponseData::getStatus, Collectors.toList()))); Map<String, List<ResponseData>> conuntink = dataarray.stream() .collect(Collectors.groupingBy(ResponseData::getSerialno, Collectors.toList())); counting.entrySet().forEach(x -> { String key = x.getKey(); List<String> val = x.getValue(); System.err.println(key + val); }); } } @Data class ResponseData { String serialno; String status; }
@Data class Item { Long id; int count; BigDecimal price; public Item(Long id, int count, BigDecimal price) { this.id = id; this.count = count; this.price = price; } public static void main(String[] args) { List<Item> items = Arrays.asList(// new Item(1000L, 2, new BigDecimal("10.00")), // new Item(1001L, 2, new BigDecimal("11.00")), // new Item(1001L, 3, new BigDecimal("11.00")), // new Item(1002L, 2, new BigDecimal("12.00")), // new Item(1002L, 2, new BigDecimal("12.00")), // new Item(1002L, 2, new BigDecimal("12.00"))); Map<Long, List<BigDecimal>> datas = items.stream().collect(Collectors.groupingBy(Item::getId, Collectors.mapping(Item::getPrice, Collectors.toList()))); System.err.println(datas); Map<Long, BigDecimal> prices = items.stream().collect(Collectors.groupingBy(Item::getId, Collectors.mapping(Item::getPrice, Collectors.reducing(BigDecimal.ZERO, BigDecimal::add)))); System.err.println(prices); } }