unknown_dcba
unknown_dcba

Reputation: 135

How can i avoid the inner loop

How can i avoid the inner loop and write this 'allocation' only with stream features? Edit: I want a list of all unique pairs catenated together, stored in l2. Example: Input: String[] l = { "a", "a", "b", "c", "d", "d", "d", "d", "a", "a", "b", "b", "c", "d" };, output: [a, a, b, c, d, d, b, b, c, d].

String[] l = { "a", "a", "b", "c", "d", "d", "d", "d", "a", "a" };
String[] l2 = 
        IntStream.iterate(0, i -> i < l.length, i -> i + 2)
        .mapToObj(i -> Objects.hash(l[i], l[i + 1]))
        .distinct()
        .map(h -> {
            for (int j = 0; j < l.length; j += 2) {
                if (h == Objects.hash(l[j], l[j + 1])) {
                    return new String[] { l[j], l[j + 1] };
                }
            }
            return null;
        })
        .flatMap(Arrays::stream)
        .toArray(String[]::new);
System.out.println(Arrays.toString(l2));

Upvotes: 4

Views: 94

Answers (2)

Bill Shubert
Bill Shubert

Reputation: 546

I'm not completely sure of what your loop is trying to achieve. Jason's loop finds all unique characters, but it looks like you're looking for all unique string pairs, then flattened. Your use of "Objects.hash()" to eliminate duplicate pairs is incorrect, it is possible for two pairs to be different but have the same hash, so Jason is right to get rid of that. If you really want a list of unique pairs catenated together, this would probably work:

IntStream.range(0, l.length / 2)
  .mapToObj(i -> List.of(l[i * 2], l[i * 2 + 1]))
  .distinct()
  .flatMap(List::stream)
  .toArray(String[]::new);

Upvotes: 5

Jason
Jason

Reputation: 5244

You don't need to do any of that. You can literally use distinct() on the stream to get all distinct values.

String[] distinct = Stream.of(l).distinct().toArray(String[]::new);

Upvotes: 0

Related Questions