Filter
Exclude
Time range
-
Near
Java17クイズ📘 Q. この結果は? List.of(1,2,3,4) .stream() .filter(n -> n % 2 == 0) .mapToInt(Integer::intValue) .sum(); A. 4 B. 6 C. 10
1
25
Replying to @unclebobmartin
Grok was able to figure out it was about bowling. import java.util.List; /** * Scores a contest with 12 stages based on the given sequence of integer entries (0-8). * Follows the specified rules for strikes, spares, opens, and the special handling for stage 12. */ public class ContestScorer { /** * Calculates the total contest score from the sequence of entries. * * @param entries the sequence of integer entries (0 through 8) * @return the total score (sum of the 12 stage values, with 0 replaced by -1) * @throws IllegalArgumentException if there are not enough entries or invalid values */ public int calculateScore(List<Integer> entries) { if (entries == null) { throw new IllegalArgumentException("Entries list cannot be null"); } // Convert to array for easier indexing int[] throwsArray = entries.stream().mapToInt(i -> i).toArray(); return calculateScore(throwsArray); } /** * Calculates the total contest score from the sequence of entries. * * @param entries the sequence of integer entries (0 through 8) * @return the total score */ public int calculateScore(int[] entries) { if (entries == null) { throw new IllegalArgumentException("Entries array cannot be null"); } int total = 0; int index = 0; final int NUM_STAGES = 12; for (int stage = 1; stage <= NUM_STAGES; stage ) { if (index >= entries.length) { throw new IllegalArgumentException("Not enough entries for stage " stage); } int first = entries[index]; validateEntry(first); index ; int value; if (first == 8) { // Strike: 8 next two (lookahead for stages 1-11) value = 8 getBonus(entries, index, 0) getBonus(entries, index, 1); // Only consume bonuses on the final stage if (stage == NUM_STAGES) { index = 2; // consume the two bonus throws } } else { if (index >= entries.length) { throw new IllegalArgumentException("Not enough entries for stage " stage); } int second = entries[index]; validateEntry(second); index ; int sum = first second; if (sum == 8) { // Spare: 8 next one (lookahead for stages 1-11) value = 8 getBonus(entries, index, 0); // Only consume bonus on the final stage if (stage == NUM_STAGES) { index ; // consume the bonus throw } } else if (sum < 8) { // Open frame value = sum; } else { throw new IllegalArgumentException("Invalid sum " sum " for stage " stage); } } // Replace 0 with -1 if (value == 0) { value = -1; } total = value; } // Optional: check that all entries were consumed (or allow extras if any) return total; } private int getBonus(int[] entries, int currentIndex, int offset) { int pos = currentIndex offset; if (pos >= entries.length) { throw new IllegalArgumentException("Not enough bonus entries"); } int val = entries[pos]; validateEntry(val); return val; } private void validateEntry(int entry) { if (entry < 0 || entry > 8) { throw new IllegalArgumentException("Entry must be between 0 and 8 inclusive"); } } }

2
369
Day 22/365: Intermediate Hashing Sliding Window Fusion in Java HashMap patterns unlocked: • Subarray Sum 0: Prefix sum repeat → zero subarray! • Two Sum (Pair Sum): Map "needed" → O(N) magic • Distinct Numbers in Window: Sliding HashMap for real-time unique count Insight: HashSet = checklist, HashMap = context (counts, indices, relations) Streams revision: • List → Map (Collectors.toMap) • Partition odd/even (partitioningBy) • Average calc (mapToInt average) #DSA #Java #CodingStreak #100DaysOfCode #HashMap #SlidingWindow #Java8 #BuildInPublic #InterviewPrep
1
4
51
✅ Day 24 of #100DaysOfCode 📌 Solved LeetCode 2293 – Min Max Game 💡 Practiced array manipulation and iterative reduction technique. Convert List to array == "From ArrayList ➝ int[] using stream().mapToInt(Integer::intValue).toArray() "🔥 #LeetCode #DSA #Java #ConsistencyWins👍
9
89
من عيوب أنك تعرف database أنك تشوف مصايب كل يوم وتضطر تمشي حالك يعني عشان تجيب average كل ما عليك تسوي Sum(rating)/Count(*) وبكذا تختصر كل شيء فالحياة لكن تلقى FindAll 😱 😰بعدها list.size() بعدها 🤢()stream().mapToInt().sum وتجي تقرأ الكود وتروح تويتر تصرخ لا تجيك جلطة
1
10
437
23 Oct 2024
No, modern Java developers are obsessed with FP: private Integer sum(List<Integer> list) { return list .stream() .mapToInt(Integer::intValue) .sum(); } Problem is that they will shoehorn this in everywhere, even when wildly inappropriate.
1
1
202
💡ArrayList Tip we can convert an ArrayList of integers to an int array. 1. "stream()" to convert ArrayList to a Stream of integers. 2. "mapToInt(Integer::intValue)" to map each Integer to its primitive int value. 3. "toArray()" - Collects the stream elements into an array."
1
4
190
Replying to @JeffQuesado
No primeiro passo não seria uma boa, pois é um int[][], a transformação para stream seria um Stream<int[]>. O mapToInt poderia ser melhor mesmo nesse caso.
1
2
259
JavaコースDAY10【Stream APIとラムダ式】 mapToInt等のIntStreamは 数値に特化した操作ができる 数値だからこそできることが増え とても便利である 大規模な業務にも高度な操作を可能にする [1時間45分] #java #プログラミング初心者 #駆け出しエンジニアと繋がりたい #プログラミング #デイトラ
12
274
#Java #javascript #learning #100DaysOfCode Day7/100 Sharing my Todays learning => To convert ArrayList to array of primitive int type Here list is reference variable for Array List. int[] res = list.stream().mapToInt(i -> i).toArray();

2
2
JavaでString配列のnewStrを、int配列に変換したい ぐぐったが int[] array = new int[newStr.length]; か int[] array = Stream.of(newStr).mapToInt(Integer::parseInt).toArray(); を使ってみてもうまくいかない でも最大値を求めるにはStirng型からint型に変換しなきゃだと思うんだけど...
1
2
久々にIntStream使った気がする。 ここら辺のプリミティブ用のStreamとか、mapToObjとかmapToIntとか、「ちょっとStreamに慣れたかな?」って人を再度苦しめてくるよね……。
1
Replying to @carldea
You need to use mapToInt or mapToLong and then there is a sum() terminal operation for both IntStream and LongStream.
1
4
var ages = new ArrayList<Integer>(); Collections.addAll(ages, 7, 14, 19, 22, 49, 49); for (int age : ages) { if (age >= 40) ages.remove(age); } System.out.println(ages.stream().mapToInt(Integer::intValue).sum()); // Thanks @surial
67% ConcurrentModificationEx.
20% 62
7% 111
6% 160
332 votes • Final results
7
1
32
Replying to @yaftu
Happy to help! :) `Stream::sum` doesn't exist - `sum` is on `IntStream` (docs.oracle.com/en/java/java…()) or `LongStream`. Use `mapToInt` or `mapToLong` to get there.

1
2
初のオフライン研修してきた😊 早起きしんどいけどそれ以上に得るもん多くて感謝🙏 学び💡 ラムダ式とstream使ってコレクションの操作。mapToIntはIntStreamを、mapToObjはstreamを返す。 曖昧です😑 ただめっちゃ便利なことだけはわかった #プログラミング初心者
12
@thomaswue @shelajev I make some microbenchmarks to compare performance of for loop vs Stream. I run them with C2 and Graal and saw some differences. 1. Trivial for loop that performs a sum of ints is 2x - 4x slower. 2. Stream that uses mapToInt().sum() is 3x quicker. Results ⬇️
1
3
optがnullの時にintを返せないし、mapToIntは存在に無理がありそう 普通にmap(arg => toInt.applyToInt(arg))ってやると思う
ゆるぼ ToIntFunction<T> toInt Optional<T> opt があります optにtoIntを適用してOptionalIntを得る方法 なんでOptionalにmapToIntOptionalみたいなのが無いんや………
1
1
Replying to @justinmalbano @java
First mapToInt then filter -> simpler code.
3