Posts

Showing posts with the label collections

Java stream averagingInt by multiple parameters

6 3 I have a class static class Student { private String surname; private String firstName; private String secondName; private int yearOfBirth; private int course; private int groupNumber; private int mathGrade; private int engGrade; private int physicGrade; private int programmingGrade; private int chemistryGrade; And there is a method that adds students to the map for the course public Map<Integer, Double> averageInt(List<Student> students) { Map<Integer, Double> map2 = students.stream() .collect(Collectors.groupingBy(Student::getCourse, Collectors.averagingInt(Student::getEngGrade))); return map2; } However, I need several...

Null coalescing operator IList, Array, Enumerable.Empty in foreach

In this question I found the following: int[] array = null; foreach (int i in array ?? Enumerable.Empty<int>()) { System.Console.WriteLine(string.Format("{0}", i)); } and int[] returnArray = Do.Something() ?? new int[] {}; and ... ?? new int[0] In a NotifyCollectionChangedEventHandler I wanted to apply the Enumerable.Empty like so: foreach (DrawingPoint drawingPoint in e.OldItems ?? Enumerable.Empty<DrawingPoint>()) this.RemovePointMarker(drawingPoint); Note: OldItems is of the type IList And it gives me: Operator '??' cannot be applied to operands of type 'System.Collections.IList' and System.Collections.Generic.IEnumerable<DrawingPoint> However foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[0]) and foreach (DrawingPoint drawingPoint in e.OldItems ?? new int[] {}) works just fine. Why is that? Why does IList ?? T[] work but IList ?? IEnumerable<T> doesn't? When using this expression: a ?? b Then b e...

Why are empty collections of different type equal?

What is mechanism below that makes equal different types? import static org.testng.Assert.assertEquals; @Test public void whyThisIsEqual() { assertEquals(new HashSet<>(), new ArrayList<>()); } The assertEquals(Collection<?> actual, Collection<?> expected) documentation says: Asserts that two collections contain the same elements in the same order. If they do not, an AssertionError is thrown. Thus the content of the collections will be compared which, in case both the collections are empty, are equal. They are not... System.out.println(new HashSet<>().equals(new ArrayList<>())); // false This is specific to testng assertEquals Looking at the documentation of that method it says: Asserts that two collections contain the same elements in the same order. And this is ridiculous to me, a Set does not have an order, per-se. Set<String> set = new HashSet<>(); set.add("hello"); set.add("from...