Repository navigation
Expand file tree
/
Copy pathtest_java_nested_structures.py
More file actions
1952 lines (1604 loc) · 63.9 KB
/
Copy pathtest_java_nested_structures.py
File metadata and controls
1952 lines (1604 loc) · 63.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from pathlib import Path
from unittest.mock import MagicMock
import pytest
from codebase_rag.tests.conftest import get_node_names, run_updater
@pytest.fixture
def java_nested_project(temp_repo: Path) -> Path:
"""Create a Java project for testing nested structures."""
project_path = temp_repo / "java_nested_test"
project_path.mkdir()
(project_path / "src").mkdir()
(project_path / "src" / "main").mkdir()
(project_path / "src" / "main" / "java").mkdir()
(project_path / "src" / "main" / "java" / "com").mkdir()
(project_path / "src" / "main" / "java" / "com" / "example").mkdir()
return project_path
def test_deeply_nested_classes(
java_nested_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test deeply nested class structures."""
test_file = (
java_nested_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "DeeplyNested.java"
)
test_file.write_text(
encoding="utf-8",
data="""
package com.example;
import java.util.*;
import java.util.function.*;
public class OuterClass {
private String outerField = "outer";
// First level nested class
public class FirstLevelNested {
private String firstField = "first";
// Second level nested class
public class SecondLevelNested {
private String secondField = "second";
// Third level nested class
public class ThirdLevelNested {
private String thirdField = "third";
// Fourth level nested class
public class FourthLevelNested {
private String fourthField = "fourth";
public void accessAllLevels() {
System.out.println(outerField); // Outer class
System.out.println(firstField); // First level
System.out.println(secondField); // Second level
System.out.println(thirdField); // Third level
System.out.println(fourthField); // Fourth level
}
// Fifth level nested class
public class FifthLevelNested {
public void deepAccess() {
accessAllLevels();
System.out.println("Deep nested access");
}
}
}
}
}
// Static nested class at first level
public static class StaticFirstLevel {
private String staticField = "static_first";
// Nested within static class
public class NestedInStatic {
public void useStaticField() {
System.out.println(staticField);
}
}
// Static within static
public static class StaticInStatic {
public void cannotAccessOuter() {
// Cannot access outerField here
System.out.println("Static in static");
}
}
}
}
// Interface nested in class
public interface NestedInterface {
void performAction();
// Nested class within interface
public static class InterfaceNestedClass {
public void implement() {
System.out.println("Class nested in interface");
}
}
// Nested interface within interface
public interface NestedInInterface {
void deepAction();
}
}
// Enum nested in class
public enum NestedEnum {
VALUE1("value1"), VALUE2("value2"), VALUE3("value3");
private final String value;
NestedEnum(String value) {
this.value = value;
}
// Method in nested enum
public String getValue() {
return value;
}
// Class nested in enum
public static class EnumNestedClass {
public void processEnumValue(NestedEnum enumValue) {
System.out.println("Processing: " + enumValue.getValue());
}
}
}
// Method to create nested instances
public void demonstrateNesting() {
// Create nested instances
FirstLevelNested first = new FirstLevelNested();
FirstLevelNested.SecondLevelNested second = first.new SecondLevelNested();
FirstLevelNested.SecondLevelNested.ThirdLevelNested third = second.new ThirdLevelNested();
FirstLevelNested.SecondLevelNested.ThirdLevelNested.FourthLevelNested fourth = third.new FourthLevelNested();
FirstLevelNested.SecondLevelNested.ThirdLevelNested.FourthLevelNested.FifthLevelNested fifth = fourth.new FifthLevelNested();
fifth.deepAccess();
// Static nested class
FirstLevelNested.StaticFirstLevel staticFirst = new FirstLevelNested.StaticFirstLevel();
FirstLevelNested.StaticFirstLevel.NestedInStatic nestedInStatic = staticFirst.new NestedInStatic();
FirstLevelNested.StaticFirstLevel.StaticInStatic staticInStatic = new FirstLevelNested.StaticFirstLevel.StaticInStatic();
// Interface and enum usage
NestedInterface.InterfaceNestedClass interfaceNested = new NestedInterface.InterfaceNestedClass();
NestedEnum.EnumNestedClass enumNested = new NestedEnum.EnumNestedClass();
enumNested.processEnumValue(NestedEnum.VALUE1);
}
}
""",
)
run_updater(java_nested_project, mock_ingestor, skip_if_missing="java")
project_name = java_nested_project.name
created_classes = get_node_names(mock_ingestor, "Class")
expected_outer_class = {
f"{project_name}.src.main.java.com.example.DeeplyNested.OuterClass",
}
missing_classes = expected_outer_class - created_classes
assert not missing_classes, (
f"Missing expected outer class: {sorted(list(missing_classes))}"
)
def test_anonymous_classes_complex(
java_nested_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test complex anonymous class patterns."""
test_file = (
java_nested_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "AnonymousComplex.java"
)
test_file.write_text(
encoding="utf-8",
data="""
package com.example;
import java.util.*;
import java.util.function.*;
import java.util.concurrent.*;
public class AnonymousComplex {
private final String instanceField = "instance";
private static final String STATIC_FIELD = "static";
// Anonymous class implementing interface
public void anonymousInterface() {
final String localVar = "local";
Runnable task = new Runnable() {
private String anonymousField = "anonymous";
@Override
public void run() {
System.out.println(instanceField); // Access outer instance
System.out.println(STATIC_FIELD); // Access static
System.out.println(localVar); // Access local final
System.out.println(anonymousField); // Access anonymous field
// Anonymous class within anonymous class
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
System.out.println("Nested anonymous: " + anonymousField);
}
});
}
// Additional method in anonymous class
public void customMethod() {
System.out.println("Custom method in anonymous class");
}
};
task.run();
// Cast to access custom method
if (task instanceof Runnable) {
// ((AnonymousRunnableSubclass) task).customMethod(); // Not accessible
}
}
// Anonymous class extending abstract class
public abstract static class AbstractProcessor {
protected String name;
public AbstractProcessor(String name) {
this.name = name;
}
public abstract void process(String data);
public void preProcess() {
System.out.println("Pre-processing with " + name);
}
}
public void anonymousAbstractClass() {
final int processingId = 123;
AbstractProcessor processor = new AbstractProcessor("Anonymous Processor") {
private List<String> processedItems = new ArrayList<>();
@Override
public void process(String data) {
preProcess(); // Call inherited method
String processed = "Processed[" + processingId + "]: " + data;
processedItems.add(processed);
System.out.println(processed);
System.out.println("Total processed: " + processedItems.size());
}
// Additional methods
public List<String> getProcessedItems() {
return new ArrayList<>(processedItems);
}
// Override toString
@Override
public String toString() {
return name + " (" + processedItems.size() + " items)";
}
};
processor.process("test data");
System.out.println(processor);
}
// Anonymous class with generics
public void anonymousWithGenerics() {
// Anonymous Comparator
Comparator<String> lengthComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
int lengthDiff = s1.length() - s2.length();
return lengthDiff != 0 ? lengthDiff : s1.compareTo(s2);
}
};
// Anonymous Function
Function<String, Integer> stringProcessor = new Function<String, Integer>() {
private Map<String, Integer> cache = new HashMap<>();
@Override
public Integer apply(String input) {
return cache.computeIfAbsent(input, s -> {
// Nested lambda within anonymous class
return s.chars().map(Character::toUpperCase).sum();
});
}
public void clearCache() {
cache.clear();
}
};
// Anonymous BiFunction with complex logic
BiFunction<List<String>, Predicate<String>, Map<String, Long>> groupCounter =
new BiFunction<List<String>, Predicate<String>, Map<String, Long>>() {
@Override
public Map<String, Long> apply(List<String> items, Predicate<String> filter) {
return items.stream()
.filter(filter)
.collect(groupingBy(
s -> s.substring(0, Math.min(1, s.length())),
Collectors.counting()
));
}
};
// Usage
List<String> items = Arrays.asList("apple", "banana", "apricot", "blueberry");
Map<String, Long> grouped = groupCounter.apply(items, s -> s.length() > 4);
}
// Anonymous class in collection operations
public void anonymousInCollections() {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
// Anonymous iterator
Iterator<String> customIterator = new Iterator<String>() {
private int index = 0;
private boolean reverse = false;
@Override
public boolean hasNext() {
return reverse ? index > 0 : index < names.size();
}
@Override
public String next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
String result = names.get(reverse ? --index : index++);
// Switch direction when reaching end
if (!hasNext()) {
reverse = !reverse;
if (reverse) {
index = names.size();
} else {
index = 0;
}
}
return result;
}
};
// Anonymous Map implementation
Map<String, String> customMap = new HashMap<String, String>() {
@Override
public String put(String key, String value) {
System.out.println("Putting: " + key + " -> " + value);
return super.put(key.toUpperCase(), value.toLowerCase());
}
@Override
public String get(Object key) {
String result = super.get(key.toString().toUpperCase());
System.out.println("Getting: " + key + " -> " + result);
return result;
}
};
customMap.put("Hello", "WORLD");
String value = customMap.get("hello");
}
// Anonymous class in event handling pattern
public interface EventListener<T> {
void onEvent(T event);
default void onError(Exception e) {
System.err.println("Error: " + e.getMessage());
}
}
public static class Event {
private final String type;
private final Object data;
private final long timestamp;
public Event(String type, Object data) {
this.type = type;
this.data = data;
this.timestamp = System.currentTimeMillis();
}
public String getType() { return type; }
public Object getData() { return data; }
public long getTimestamp() { return timestamp; }
}
public void anonymousEventHandling() {
final AtomicInteger eventCount = new AtomicInteger(0);
EventListener<Event> complexListener = new EventListener<Event>() {
private Map<String, Integer> eventTypeCounts = new HashMap<>();
private List<Event> recentEvents = new ArrayList<>();
@Override
public void onEvent(Event event) {
eventCount.incrementAndGet();
// Update type counts
eventTypeCounts.merge(event.getType(), 1, Integer::sum);
// Keep only recent events
recentEvents.add(event);
if (recentEvents.size() > 10) {
recentEvents.remove(0);
}
// Complex processing based on event type
switch (event.getType()) {
case "USER_LOGIN" -> handleUserLogin(event);
case "DATA_UPDATE" -> handleDataUpdate(event);
case "SYSTEM_ERROR" -> handleSystemError(event);
default -> handleGenericEvent(event);
}
// Nested anonymous class for async processing
CompletableFuture.runAsync(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100); // Simulate processing
System.out.println("Async processed: " + event.getType());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
onError(e);
}
}
});
}
private void handleUserLogin(Event event) {
System.out.println("User login processed");
}
private void handleDataUpdate(Event event) {
System.out.println("Data update processed");
}
private void handleSystemError(Event event) {
System.err.println("System error: " + event.getData());
}
private void handleGenericEvent(Event event) {
System.out.println("Generic event: " + event.getType());
}
@Override
public void onError(Exception e) {
EventListener.super.onError(e);
System.err.println("Event processing failed for event count: " + eventCount.get());
}
};
// Test events
complexListener.onEvent(new Event("USER_LOGIN", "user123"));
complexListener.onEvent(new Event("DATA_UPDATE", "dataset1"));
complexListener.onEvent(new Event("SYSTEM_ERROR", "Out of memory"));
}
}
""",
)
run_updater(java_nested_project, mock_ingestor, skip_if_missing="java")
project_name = java_nested_project.name
created_classes = get_node_names(mock_ingestor, "Class")
expected_classes = {
f"{project_name}.src.main.java.com.example.AnonymousComplex.AnonymousComplex",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_local_classes_in_methods(
java_nested_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test local classes defined within methods."""
test_file = (
java_nested_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "LocalClasses.java"
)
test_file.write_text(
encoding="utf-8",
data="""
package com.example;
import java.util.*;
import java.util.function.*;
public class LocalClasses {
private String instanceField = "instance";
// Method with simple local class
public void methodWithLocalClass() {
final String methodLocal = "method_local";
int methodVar = 42;
// Local class definition
class LocalCalculator {
private int localField = 100;
public int calculate() {
// Can access final/effectively final variables
return localField + methodVar + methodLocal.length();
}
public void printInfo() {
System.out.println("Instance field: " + instanceField);
System.out.println("Method local: " + methodLocal);
System.out.println("Method var: " + methodVar);
System.out.println("Local field: " + localField);
}
}
// Use local class
LocalCalculator calculator = new LocalCalculator();
int result = calculator.calculate();
calculator.printInfo();
System.out.println("Calculation result: " + result);
}
// Method with local class implementing interface
public Comparator<String> createCustomComparator(boolean caseSensitive) {
final String prefix = caseSensitive ? "CS_" : "CI_";
class CustomComparator implements Comparator<String> {
private int comparisonCount = 0;
@Override
public int compare(String s1, String s2) {
comparisonCount++;
System.out.println(prefix + "Comparison #" + comparisonCount);
if (caseSensitive) {
return s1.compareTo(s2);
} else {
return s1.compareToIgnoreCase(s2);
}
}
public int getComparisonCount() {
return comparisonCount;
}
@Override
public String toString() {
return prefix + "Comparator (comparisons: " + comparisonCount + ")";
}
}
return new CustomComparator();
}
// Method with multiple local classes
public void multipleLocalClasses() {
final List<String> sharedData = new ArrayList<>();
// First local class
class DataProducer {
private String producerName;
public DataProducer(String name) {
this.producerName = name;
}
public void produce() {
for (int i = 0; i < 5; i++) {
String data = producerName + "_item_" + i;
sharedData.add(data);
System.out.println("Produced: " + data);
}
}
}
// Second local class
class DataConsumer {
private String consumerName;
private List<String> consumedItems = new ArrayList<>();
public DataConsumer(String name) {
this.consumerName = name;
}
public void consume() {
while (!sharedData.isEmpty()) {
String item = sharedData.remove(0);
consumedItems.add(item);
System.out.println(consumerName + " consumed: " + item);
}
}
public List<String> getConsumedItems() {
return new ArrayList<>(consumedItems);
}
}
// Third local class for processing
class DataProcessor {
public void process(List<String> items) {
System.out.println("Processing " + items.size() + " items:");
items.forEach(item -> System.out.println(" - " + item.toUpperCase()));
}
}
// Use local classes
DataProducer producer = new DataProducer("Producer1");
DataConsumer consumer = new DataConsumer("Consumer1");
DataProcessor processor = new DataProcessor();
producer.produce();
consumer.consume();
processor.process(consumer.getConsumedItems());
}
// Local class with generics
public <T> Function<T, String> createToStringFunction(String format) {
final String template = format != null ? format : "Value: %s";
class ToStringConverter<U> implements Function<U, String> {
private int conversionCount = 0;
@Override
public String apply(U input) {
conversionCount++;
if (input == null) {
return template.replace("%s", "null");
}
return template.replace("%s", input.toString()) + " (#" + conversionCount + ")";
}
public int getConversionCount() {
return conversionCount;
}
}
@SuppressWarnings("unchecked")
Function<T, String> converter = (Function<T, String>) new ToStringConverter<T>();
return converter;
}
// Nested method with local class
public void nestedMethodsWithLocalClasses() {
final String outerMethodVar = "outer_method";
class OuterLocalClass {
public void methodInLocalClass() {
final String innerMethodVar = "inner_method";
// Local class within method of local class
class InnerLocalClass {
public void deepMethod() {
System.out.println("Instance: " + instanceField);
System.out.println("Outer method: " + outerMethodVar);
System.out.println("Inner method: " + innerMethodVar);
// Anonymous class within local class within local class
Runnable task = new Runnable() {
@Override
public void run() {
System.out.println("Anonymous in local in local: " +
instanceField + ", " + outerMethodVar + ", " + innerMethodVar);
}
};
task.run();
}
}
InnerLocalClass inner = new InnerLocalClass();
inner.deepMethod();
}
}
OuterLocalClass outer = new OuterLocalClass();
outer.methodInLocalClass();
}
// Local class in static method
public static void staticMethodWithLocalClass() {
final String staticMethodVar = "static_method";
class StaticLocalClass {
private String localField = "static_local";
public void showAccess() {
// Can access static method variables
System.out.println("Static method var: " + staticMethodVar);
System.out.println("Local field: " + localField);
// Cannot access instance fields
// System.out.println("Instance field: " + instanceField); // COMPILE ERROR
}
// Can have static members in local class (Java 16+)
public static void staticMethodInLocalClass() {
System.out.println("Static method in local class");
}
}
StaticLocalClass localInstance = new StaticLocalClass();
localInstance.showAccess();
StaticLocalClass.staticMethodInLocalClass();
}
// Local class in constructor
public LocalClasses(String initValue) {
final String constructorVar = "constructor_" + initValue;
class ConstructorLocalClass {
public void initialize() {
instanceField = constructorVar + "_initialized";
System.out.println("Initialized with: " + instanceField);
}
}
ConstructorLocalClass initializer = new ConstructorLocalClass();
initializer.initialize();
}
// Default constructor
public LocalClasses() {
this("default");
}
// Local class in lambda context
public void localClassInLambdaContext() {
final List<String> items = Arrays.asList("apple", "banana", "cherry");
items.forEach(item -> {
final String processedItem = item.toUpperCase();
// Local class within lambda
class LambdaLocalProcessor {
public String process() {
return "Processed: " + processedItem + " (length: " + processedItem.length() + ")";
}
}
LambdaLocalProcessor processor = new LambdaLocalProcessor();
System.out.println(processor.process());
});
}
// Local class accessing method parameters
public String processData(String data, Function<String, String> transformer) {
final String methodParam = data;
final Function<String, String> methodTransformer = transformer;
class ParameterProcessor {
public String process() {
String transformed = methodTransformer.apply(methodParam);
return "Parameter processed: " + transformed;
}
}
ParameterProcessor processor = new ParameterProcessor();
return processor.process();
}
}
""",
)
run_updater(java_nested_project, mock_ingestor, skip_if_missing="java")
project_name = java_nested_project.name
created_classes = get_node_names(mock_ingestor, "Class")
expected_classes = {
f"{project_name}.src.main.java.com.example.LocalClasses.LocalClasses",
}
missing_classes = expected_classes - created_classes
assert not missing_classes, (
f"Missing expected classes: {sorted(list(missing_classes))}"
)
def test_lambda_edge_cases(
java_nested_project: Path,
mock_ingestor: MagicMock,
) -> None:
"""Test complex lambda expression edge cases."""
test_file = (
java_nested_project
/ "src"
/ "main"
/ "java"
/ "com"
/ "example"
/ "LambdaEdgeCases.java"
)
test_file.write_text(
encoding="utf-8",
data="""
package com.example;
import java.util.*;
import java.util.function.*;
import java.util.concurrent.*;
public class LambdaEdgeCases {
// Lambda capturing different types of variables
public void variableCapture() {
final String finalVar = "final";
String effectivelyFinal = "effectively_final";
// Don't modify effectivelyFinal after this point
AtomicInteger counter = new AtomicInteger(0);
List<String> mutableList = new ArrayList<>();
// Lambda capturing final variable
Supplier<String> finalCapture = () -> "Final: " + finalVar;
// Lambda capturing effectively final variable
Supplier<String> effectivelyFinalCapture = () -> "Effectively final: " + effectivelyFinal;
// Lambda capturing mutable object (reference is final)
Consumer<String> listAdder = item -> {
mutableList.add(item);
counter.incrementAndGet();
};
// Lambda with complex capture
Function<String, String> complexCapture = input -> {
return finalVar + "_" + effectivelyFinal + "_" + input + "_" + counter.get();
};
// Use lambdas
listAdder.accept("item1");
listAdder.accept("item2");
System.out.println(finalCapture.get());
System.out.println(effectivelyFinalCapture.get());
System.out.println(complexCapture.apply("test"));
System.out.println("List contents: " + mutableList);
}
// Recursive lambda expressions
public void recursiveLambdas() {
// Recursive lambda using method reference to itself
Function<Integer, Integer> factorial = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer n) {
return n <= 1 ? 1 : n * this.apply(n - 1);
}
};
System.out.println("Factorial 5: " + factorial.apply(5));
// Recursive lambda with explicit self-reference
class RecursiveLambdaHolder {
Function<Integer, Integer> fibonacci = n -> {
if (n <= 1) return n;
return this.fibonacci.apply(n - 1) + this.fibonacci.apply(n - 2);
};
}
RecursiveLambdaHolder holder = new RecursiveLambdaHolder();
System.out.println("Fibonacci 10: " + holder.fibonacci.apply(10));
// Mutual recursion with lambdas
class MutualRecursion {
Function<Integer, Boolean> isEven = n -> n == 0 || isOdd.apply(n - 1);
Function<Integer, Boolean> isOdd = n -> n != 0 && isEven.apply(n - 1);
}
MutualRecursion mr = new MutualRecursion();
System.out.println("Is 4 even: " + mr.isEven.apply(4));
System.out.println("Is 5 odd: " + mr.isOdd.apply(5));
}
// Lambda expressions with exception handling
public void lambdaExceptionHandling() {
// Functional interface that throws checked exception
@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception> {
R apply(T t) throws E;
}
// Wrapper to convert throwing function to regular function
Function<String, Integer> wrappedFunction = input -> {
try {
ThrowingFunction<String, Integer, NumberFormatException> parser = Integer::parseInt;
return parser.apply(input);
} catch (NumberFormatException e) {
System.err.println("Parse error: " + e.getMessage());
return 0;
}
};
// Lambda with try-catch
Consumer<String> safeProcessor = input -> {
try {
int value = Integer.parseInt(input);
System.out.println("Processed value: " + value * 2);
} catch (NumberFormatException e) {
System.err.println("Invalid input: " + input);
} catch (Exception e) {
System.err.println("Unexpected error: " + e.getMessage());
}
};
// Lambda that rethrows as runtime exception
Function<String, Integer> rethrowing = input -> {
try {
return Integer.parseInt(input);
} catch (NumberFormatException e) {
throw new RuntimeException("Failed to parse: " + input, e);
}
};
// Test exception handling
List<String> inputs = Arrays.asList("123", "invalid", "456", "bad");
inputs.forEach(safeProcessor);
inputs.stream()
.map(wrappedFunction)
.forEach(result -> System.out.println("Result: " + result));
}
// Complex lambda chaining and composition
public void lambdaComposition() {
// Function composition
Function<String, String> trim = String::trim;
Function<String, String> upper = String::toUpperCase;
Function<String, Integer> length = String::length;
Function<Integer, String> format = i -> String.format("[%d chars]", i);
Function<String, String> pipeline = trim
.andThen(upper)
.andThen(length)
.andThen(format);
// Predicate composition
Predicate<String> notNull = Objects::nonNull;
Predicate<String> notEmpty = s -> !s.isEmpty();
Predicate<String> hasContent = notNull.and(notEmpty);
Predicate<String> isLong = s -> s.length() > 5;
Predicate<String> isValidAndLong = hasContent.and(isLong);
// Consumer composition
Consumer<String> printer = System.out::println;
Consumer<String> logger = s -> System.err.println("LOG: " + s);
Consumer<String> combined = printer.andThen(logger);
// Complex composition example
List<String> inputs = Arrays.asList(" hello world ", "", null, "short", " this is a long string ");
inputs.stream()