Skip to content

Latest commit

 

History

History
555 lines (459 loc) · 15.9 KB

Top_java_8_stream_questions_so.md

File metadata and controls

555 lines (459 loc) · 15.9 KB
  • By Java 8
// if choices are unique by name.
Map<String, Choice> result = choices.stream()
                                    .collect(Collectors.toMap(Choice::getName, Function.identity()));
// owtherwise group by
Map<String, List<Choice>> result = choices.stream()
                                          .collect(Collectors.groupingBy(Choice::getName));
  • By abacus-common
Map<String, Choice> result = Stream.of(choices).toMap(Choice::getName, Fn.identity());

// group by
Map<String, List<Choice>> result = Stream.of(choices).groupTo(Choice::getName);

###Map<String,List<String>> to Pair<String,String>

  • By Java 8
List<Pair<String, String>> result =
    map.entrySet()
       .stream()
       .flatMap(
           entry -> entry.getValue()
                         .stream()
                         .map(string -> new Pair<>(entry.getKey(), string)))
       .collect(Collectors.toList());
  • By abacus-common
List<Pair<String, String>> result = Stream.of(map)
        .flatMap(e -> Stream.of(e.getValue()).map(v -> Pair.of(e.getKey(), v))).toList();

  • By Java 8
targetLongList = sourceLongList.stream()
                               .filter(l -> l > 100)
                               .collect(Collectors.toList());
  • By abacus-common
targetLongList = Stream.of(sourceLongList).filter(l -> l > 100).toList();

  • By Java 8
???
  • By abacus-common
stream.parallel(threadNum);

  • By Java 8
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
         .filter(i -> names[i].length() <= i)
         .mapToObj(i -> names[i])
         .collect(Collectors.toList());
  • By abacus-common
String[] names = {"Sam", "Pamela", "Dave", "Pascal", "Erik"};
IntStream.range(0, names.length)
         .filter(i -> names[i].length() <= i)
         .mapToObj(i -> names[i])
         .toList();

// Or: indexed for any type of collection/iterator.
Stream.of(collection).indexed()...;

  • By Java 8
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(className -> try {
                            Class.forName(className))
                        } catch (ClassNotFoundException ) {
                            throw new RuntimeException(e);
                        }
              .collect(Collectors.toList());
  • By abacus-common
Stream.of("java.lang.Object", "java.lang.Integer", "java.lang.String")
              .map(Fn.ff(className -> Class.forName(className)))
              .toList();

  • By Java 8
Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
          .findFirst();
  • By abacus-common
Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(Optional::stream)
          .first();

  • By Java 8
// ??? No easy way to do it until Java 9
IntStream
    .iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(System.out::println);
  • By abacus-common
IntStream
    .iterate(1, n -> n + 1)
    .takeWhile(n -> n < 10)
    .forEach(Fn.println);

  • By Java 8
List<Answer> answerList = new ArrayList<>();
answerList.add(new Answer(1, true));
answerList.add(new Answer(2, true));
answerList.add(new Answer(3, null));

Map<Integer, Boolean> answerMap = answerList.stream()
          .collect(Collectors.toMap(Answer::getId, Answer::getAnswer)); // throw NullPointerException
  • By abacus-common
// Works well.
Map<Integer, Boolean> answerMap = answerList.stream().toMap(Answer::getId, Answer::getAnswer);

  • By Java 8
Stream stream = Stream.concat(
                       Stream.concat(
                              stream1.filter(x -> x!=0), stream2)
                              .filter(x -> x!=1),
                                  Stream.of(element))
                                  .filter(x -> x!=2);
  • By abacus-common
stream1.append(stream2).append(element);

  • By Java 8
Map<String, String> x;
Map<String, Integer> y =
    x.entrySet().stream()
        .collect(Collectors.toMap(
            e -> e.getKey(),
            e -> Integer.parseInt(e.getValue())
        ));
  • By abacus-common
Map<String, Integer> y = Stream.of(x).toMap(e -> e.getKey(), e -> Integer.parseInt(e.getValue()));

  • By Java 8
???
  • By abacus-common

Yes, with the most beautiful design: Pair, Triple, Tuple


  • By Java 8
List<User> resultUserList = users.stream()
        .filter(user -> user.getId() == 1)
        .limit(2)
        .collect(Collectors.toList());
if (resultUserList.size() != 1) {
    throw new IllegalStateException();
}
User resultUser = resultUserList.get(0);

// Or by singletonCollector()
public static <T> Collector<T, ?, T> singletonCollector() {
    return Collectors.collectingAndThen(
            Collectors.toList(),
            list -> {
                if (list.size() != 1) {
                    throw new IllegalStateException();
                }
                return list.get(0);
            }
    );
}
  • By abacus-common
users.stream().filter(user -> user.getId() == 1).onlyOne();

  • By Java 8
// Answers are included in the above link.
  • By abacus-common

Kotlin vs Java 8 on Collection


  • By Java 8
???
  • By abacus-common
String[] a = {"a", "b", "c"};
String[] b = {"1", "2", "3"};
Stream.zip(a, b, Pair::of)...;

  • By Java 8
Map<String, String> phoneBook = 
    people.stream()
          .collect(Collectors.toMap(
             Person::getName,
             Person::getAddress,
             (address1, address2) -> {
                 System.out.println("duplicate key found!");
                 return address1;
             }
          ));
  • By abacus-common
Map<String, String> phoneBook = people.stream().toMap(Person::getName, Person::getAddress, Fn.ignoringMerger()); // Fn.replacingMerger()

  • By Java 8
Stream.of(objects).filter(c -> c instanceof Client)
    .map(c -> ((Client) c).getID()).forEach(System.out::println);
  • By abacus-common
Stream.of(objects).select(Client.class).forEach(Fn.println);

  • By Java 8
stream.forEach(a -> safeFoo(a));
  
private void safeFoo(final A a) {
    try {
        a.foo();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}
  • By abacus-common
stream.forEach(a -> Try.run(() -> a.foo()));

  • By Java 8
???
  • By abacus-common
stream.reversed()...
IntStream.of(1, 5, 3).reverseSorted()...

  • By Java 8
// For Array/List only.
IntStream.range(1, arrayList.size())
             .mapToObj(i -> new Pair(arrayList.get(i-1), arrayList.get(i)))
             .forEach(System.out::println);
// There is no general solution Stream created from iterator/collection..
  • By abacus-common
// For any stream created from iterator/Collection/Array/List...
stream().slidingMap(Pair::of).forEach(Fn.println());

  • By Java 8
T last = stream.reduce((a, b) -> b).orElse(null);
  • By abacus-common
T last = stream.last().orElse(null);

  • By Java 8
???
  • By abacus-common
stream.split(batchSize)...

  • By Java 8
Map<String, Integer> m1 = ImmutableMap.of("a", 2, "b", 3);
Map<String, Integer> m2 = ImmutableMap.of("a", 3, "c", 4);

Map<String, Integer> mx = Stream.of(m1, m2)
    .map(Map::entrySet)          // converts each map into an entry set
    .flatMap(Collection::stream) // converts each set into an entry stream, then
                                 // "concatenates" it in place of the original set
    .collect(
        Collectors.toMap(        // collects into a map
            Map.Entry::getKey,   // where each entry is based
            Map.Entry::getValue, // on the entries in the stream
            Integer::max         // such that if a value already exist for
                                 // a given key, the max of the old
                                 // and new value is taken
        )
    );
  • By abacus-common
Stream.of(m1).append(m2.entrySet()).toMap(Fn.key(), Fn.value(), Integer::max);

  • By Java 8
List<String> list = ...;
return IntStream.range(0, list.size())
    .filter(n -> n % 3 == 0)
    .mapToObj(list::get)
    .collect(Collectors.toList());
  • By abacus-common
Stream.of(list).step(3).toList();

  • By Java 8
Integer[] numbers = new Integer[] { 1, 2, 1, 3, 4, 4 };
Set<Integer> allItems = new HashSet<>();
Set<Integer> duplicates = Arrays.stream(numbers)
        .filter(n -> !allItems.add(n)) //Set.add() returns false if the item was already in the set.
        .collect(Collectors.toSet());
  • By abacus-common
Stream.of(numbers).groupByToEntry(Fn.identity(), Fn.counting()).filterByValue(occur -> occur > 1).keys().toList();
// Or:
Multiset.of(numbers).entryStream().filterByValue(occur -> occur > 1).keys().toList();

  • By Java 8
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

// Or:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}
  • By abacus-common
Stream.of(multiDataPoints)
    .flatMap(mdp -> Stream.of(mdp.keyToData).map(e -> Pair.of(e.getKey(), new DataPoint(mdp.timestamp, e.getValue()))))
    .groupBy(Entry::getKey, Entry::getValue).map(e -> new DataSet(e.getKey(), e.getValue())).toList();

  • By Java 8
String result = "Hello world."
  .codePoints()
//.parallel()  // uncomment this line for large strings
  .map(c -> c == ' ' ? ' ': '*')
  .collect(StringBuilder::new,
           StringBuilder::appendCodePoint, StringBuilder::append)
  .toString();
  • By abacus-common
CharStream.of(result).map(c -> c == ' ' ? ' ': '*').println();

  • By Java 8
???
  • By abacus-common
Stream.of(resultSet)...
// Or:
Stream.of(entityClass, resultSet)...
//Or:
sqlExecutor.stream(sql, parameters);

  • By Java 8
int[] one = new int[]{1, 2, 3};
int[] two = new int[]{3, 4};
List<IntIntPair> list = new ArrayList<>();
IntStream.of(one).forEach(i ->
        IntStream.of(two).mapToObj(j -> PrimitiveTuples.pair(i, j)).forEach(list::add));
System.out.println(list);
  • By abacus-common
Stream.of(1, 2, 3).cartesianProduct(Arrays.asList(3, 4)).forEach(Fn.println());