How to use threads with interfering methods and constructors, and why not use .peek ()?

I will show a simplified example of my problem to demonstrate it.

let's say I'm trying to convert old Java code to java 8 code for style and parallelization purposes (what I am doing).

this is the code:

    public static boolean deleteTester(List<Integer> keys) {
        DHeap dHeap = new DHeap(d, keys.size());
        DHeap_Item[] DHeap_ItemArray = keysListToDHeap_ItemArray(keys);
        dHeap.arrayToHeap(DHeap_ItemArray);

        for (int i = 0; i < keys.size(); i++) {
            keys.set(i, null);
            dHeap.delete(DHeap_ItemArray[i]);
            if (!someTest(keys, dHeap.getList()))
                return false;
        }
        return true;
    }

There are several problems with the conversion:

  • I need to check every iteration, so I cannot reduce / collect, and then check.
  • I get access to the array and object of the data structure (for which the tester is intended), which means that it is not a hindrance and does not work without citizenship.

Here is my attempt to replace the for loop:

    return IntStream.range(0, keys.size())
            //.parallel()
            .peek(idx -> keys.set(idx, null))
            .peek(idx -> dHeap.delete(DHeap_ItemArray[idx]))
            .allMatch(e -> someTest(keys, dHeap.getList()));

which is much shorter and more readable, but "breaks the rules" and as a result cannot be parallel.

So my questions are:

  • .parallal()? ( ex.)
  • peek()? .
  • ?
  • "" java 8 ?
  • ?

, . java 8, , .

+4
2

Q: .parallal()?

Q: ?

, , , :

stream.peek(System.out::println).allMatch(...);

, , :

stream.peek(it->{synchronized(lock){ keys.set(idx, null); }}).allMatch(...);

Q: peek()?

peek(), peek(), , :

boolean foo(){ stream.peek(...).allMatch(..); }

//a violate rule
Stream<?> foo(){
  /*you need avoiding using peek() here since you can't control the stream*/
}

Q: "" java 8 ?

, java.util.stream.

+2

peek, . API , peek , allMatch. , anyMatch , peek , , anyMatch.

, peek . :

List<List<Integer>> data = Arrays.asList(
    Arrays.asList(1,2), 
    Arrays.asList(3,4,5), 
    Arrays.asList(6,7));

data.stream()
    .flatMap(List::stream)
    .peek(System.out::println)
    .allMatch(x -> x < 4);

, 3, 5.

+1

Source: https://habr.com/ru/post/1680085/


All Articles