Skip to content

feat: add ToMap for stream #301

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 14, 2025
Merged

feat: add ToMap for stream #301

merged 3 commits into from
Apr 14, 2025

Conversation

ppd324
Copy link

@ppd324 ppd324 commented Apr 2, 2025

add ToMap for stream

@cannian1
Copy link
Collaborator

cannian1 commented Apr 6, 2025

@ppd324 main branch was frozen, merge into rc branch.

@ppd324 ppd324 changed the base branch from main to rc April 7, 2025 02:15
cannian1
cannian1 previously approved these changes Apr 7, 2025
@ppd324
Copy link
Author

ppd324 commented Apr 7, 2025

Is it necessary to add a merge function to the ToMap method to merge key conflicts?
like this:

func ToMap[T any, K comparable, V any](s Stream[T], mapper func(item T) (K, V), mergeFunc func(existing, new V) V) map[K]V {
	m := make(map[K]V, len(s.source))
	for _, v := range s.source {
		key, value := mapper(v)
		if existing, ok := m[key]; ok {
			if mergeFunc != nil {
				m[key] = mergeFunc(existing, value)
				continue
			}
		}
		m[key] = value
	}
	return m
} 

@cannian1
Copy link
Collaborator

func ToMap[T any, K comparable, V any](s Stream[T], mapper func(item T) (K, V), mergeFunc func(existing, new V) V) map[K]V {
	m := make(map[K]V, len(s.source))
	for _, v := range s.source {
		key, value := mapper(v)
		if existing, ok := m[key]; ok {
			if mergeFunc != nil {
				m[key] = mergeFunc(existing, value)
				continue
			}
		}
		m[key] = value
	}
	return m
} 

I think it's better to split this into two functions

Simpler API for common cases

func ToMap[T any, K comparable, V any](s Stream[T], mapper func(item T) (K, V)) map[K]V {
	return ToMapWithMerge(s, mapper, nil)
}

func ToMapWithMerge[T any, K comparable, V any](s Stream[T], mapper func(item T) (K, V), mergeFunc func(existing, new V) V) map[K]V 

@ppd324 ppd324 requested a review from cannian1 April 14, 2025 02:27
@cannian1 cannian1 merged commit c841a5b into duke-git:rc Apr 14, 2025
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants